23 Commits
Author SHA1 Message Date
fsylvain e0fa433ff9 docs: release notes format and patch notes for v2.0.0-beta to v2.4.0-beta 2026-09-30 03:11:37 +02:00
fsylvain 142325730d feat: users row actions "Cancel invite" on Pending rows and "Renew invite" on Expired rows 2026-09-30 02:48:49 +02:00
fsylvain 1ece778caf feat: UsersTable and UserCardList get Email, Display name (dash when empty), Role (new RoleBadge), Invite status and Created 2026-09-30 02:00:46 +02:00
fsylvain 153fd8719a feat: invite management API: DELETE /v1/user/invite/:id (204, cancels a pending invite) and POST /v1/user/invite/:id/renew (200, new code, expires_at = now+3d, created_at = now, resends the invitation email, old link dead) 2026-09-30 01:36:43 +02:00
fsylvain 461e93e3b5 feat: add Role (owner|admin) to the user domain, persistence model and mapper 2026-09-30 00:58:58 +02:00
fsylvain 162fea4afb feat: settings page, sidebar and drawer destination "Settings" (icon settings, after Integration), route /settings (verified), showing only the running build's Version 2026-09-30 00:19:29 +02:00
fsylvain b146dfead7 fix: desktop account menu icons, labels and check mark are now centred in their 32 px rows 2026-09-29 23:36:42 +02:00
fsylvain 27dadbbfa6 fix: account menu matches the redesigned board: System, Light, Dark stay in the menu and the sheet, and the visual-check exception on profile "Account menu" in web/visual/states.ts is removed 2026-09-29 23:31:04 +02:00
fsylvain 6dc47789ef chore: groundwork for new design and features related to users and settings 2026-09-29 23:19:41 +02:00
fsylvain 65ced64568 fix: "save X min ago" only min to min/hours/days 2026-09-29 22:56:05 +02:00
fsylvain c40522a09f fix: scrollable toolbar in mobile editor 2026-09-29 22:53:49 +02:00
fsylvain da36c78bc0 refac: hardening pass with multiple overhauls 2026-09-29 10:55:23 +02:00
fsylvain b0f7b7892b feat(SPA): profile page, display name and the new account menu 2026-09-29 10:13:09 +02:00
fsylvain 55525c06d6 feat: invitation accept screen and api 2026-09-29 09:21:53 +02:00
fsylvain 310cfd528e chore: new design for invitations accept 2026-09-29 08:41:54 +02:00
fsylvain 6afffc1984 feat(SPA): users page and invite modal 2026-09-29 08:35:14 +02:00
fsylvain acdef18b37 feat(API): user invitations and emails 2026-09-29 07:15:17 +02:00
fsylvain 7aae704d0a feat(API): optional display name on users 2026-09-29 06:52:58 +02:00
fsylvain 792aba433d chore: new design groundwork for next features 2026-09-29 06:32:46 +02:00
fsylvain b29d0ed045 feat: editor image removal QOLs 2026-09-29 02:44:31 +02:00
fsylvain 0fc00ceeff refac: cleaning round for image cropping/resizing 2026-09-28 07:56:13 +02:00
fsylvain e15f444603 feat: image cropping / resizing T0 2026-09-28 07:46:12 +02:00
fsylvain cb05b38f36 feat: password reset full design and flow 2026-09-28 05:06:16 +02:00
202 changed files with 21457 additions and 924 deletions

No files matched your search

+32 -2
View File
@@ -3,6 +3,7 @@ package api
import (
domainArticle "RenewCMS/internal/domain/article"
domainImage "RenewCMS/internal/domain/image"
domainInvite "RenewCMS/internal/domain/invite"
domainMail "RenewCMS/internal/domain/mail"
domainUser "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/config"
@@ -11,6 +12,7 @@ import (
"RenewCMS/internal/infrastructure/persistence/models"
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
"RenewCMS/internal/infrastructure/useCases"
"fmt"
"os"
"path/filepath"
@@ -33,32 +35,51 @@ type UseCases struct {
CancelRegistrationUseCase *useCases.CancelRegistrationUseCase
RequestPasswordResetUseCase *useCases.RequestPasswordResetUseCase
ResetPasswordUseCase *useCases.ResetPasswordUseCase
UpdateUserProfileUseCase *useCases.UpdateUserProfileUseCase
ListUsersUseCase *useCases.ListUsersUseCase
CreateInviteUseCase *useCases.CreateInviteUseCase
CancelInviteUseCase *useCases.CancelInviteUseCase
RenewInviteUseCase *useCases.RenewInviteUseCase
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
GetInviteUseCase *useCases.GetInviteUseCase
AcceptInviteUseCase *useCases.AcceptInviteUseCase
SendMailUseCase *useCases.SendMailUseCase
CreateImageUseCase *useCases.CreateImageUseCase
DeleteImageUseCase *useCases.DeleteImageUseCase
GetSettingsUseCase *useCases.GetSettingsUseCase
}
type Repositories struct {
ArticleRepo domainArticle.Repository
UserRepo domainUser.Repository
ImageRepo domainImage.Repository
InviteRepo domainInvite.Repository
MailRepo domainMail.Repository
}
const sqliteBusyTimeoutMs = 5000
func SQLiteDSN(dbName string) string {
return fmt.Sprintf("%s?_pragma=busy_timeout(%d)", dbName, sqliteBusyTimeoutMs)
}
func getDb(dbName string) *gorm.DB {
if err := os.MkdirAll(filepath.Dir(dbName), os.ModePerm); err != nil {
panic("Unable to create necessary subdirectories: " + err.Error())
}
db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{})
db, err := gorm.Open(sqlite.Open(SQLiteDSN(dbName)), &gorm.Config{})
if err != nil {
panic("Unable to open the database: " + err.Error())
}
if err := db.AutoMigrate(&models.Article{}, &models.User{}); err != nil {
if err := db.AutoMigrate(&models.Article{}, &models.User{}, &models.Invite{}); err != nil {
panic("Failed to migrate database: " + err.Error())
}
if err := persistence.BackfillUserRoles(db); err != nil {
panic("Failed to backfill user roles: " + err.Error())
}
return db
}
@@ -67,6 +88,7 @@ func getRepositories(db *gorm.DB, settings config.Settings) *Repositories {
ArticleRepo: persistence.NewArticleRepository(db),
UserRepo: persistence.NewUserRepository(db),
ImageRepo: persistence.NewImageRepository(db, settings.UploadDir),
InviteRepo: persistence.NewInviteRepository(db),
MailRepo: mailer.NewMailRepository(settings.Smtp),
}
}
@@ -88,10 +110,18 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
CancelRegistrationUseCase: useCases.NewCancelRegistrationUseCase(repos.UserRepo),
RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher),
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo),
ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo),
CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
CancelInviteUseCase: useCases.NewCancelInviteUseCase(repos.InviteRepo),
RenewInviteUseCase: useCases.NewRenewInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(repos.UserRepo, repos.InviteRepo),
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher),
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo),
DeleteImageUseCase: useCases.NewDeleteImageUseCase(repos.ImageRepo),
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
}
}
+102
View File
@@ -0,0 +1,102 @@
package auth
import (
"RenewCMS/api/pkg/apperr"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/invite"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"github.com/go-chi/jwtauth/v5"
)
type AcceptInviteHandler struct {
Token *jwtauth.JWTAuth
GetInviteUseCase *useCases.GetInviteUseCase
AcceptInviteUseCase *useCases.AcceptInviteUseCase
IsProduction bool
}
type AcceptInviteRequest struct {
Code string `json:"code" validate:"required"`
Username string `json:"username" validate:"required,min=3,max=20"`
Password string `json:"password" validate:"required,min=8"`
}
type inviteEmailResponse struct {
Email string `json:"email"`
}
func NewAcceptInviteHandler(getInvite *useCases.GetInviteUseCase, acceptInvite *useCases.AcceptInviteUseCase, token *jwtauth.JWTAuth, isProduction bool) *AcceptInviteHandler {
return &AcceptInviteHandler{
Token: token,
GetInviteUseCase: getInvite,
AcceptInviteUseCase: acceptInvite,
IsProduction: isProduction,
}
}
func (h *AcceptInviteHandler) GetInvite(w http.ResponseWriter, r *http.Request) {
found, err := h.GetInviteUseCase.GetInvite(r.URL.Query().Get("c"))
if err != nil {
writeAcceptInviteError(w, err)
return
}
body, err := json.Marshal(inviteEmailResponse{Email: found.Email})
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
func (h *AcceptInviteHandler) AcceptInvite(w http.ResponseWriter, r *http.Request) {
var request AcceptInviteRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
createdUser, err := h.AcceptInviteUseCase.AcceptInvite(useCases.AcceptInviteCommand{
Code: request.Code,
Username: request.Username,
Password: request.Password,
})
if err != nil {
writeAcceptInviteError(w, err)
return
}
if err := setJwtCookie(w, h.Token, h.IsProduction, createdUser); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
message, _ := json.Marshal(map[string]any{"message": "Invite accepted! HTTPonly jwt cookie created"})
_, _ = w.Write(message)
}
func writeAcceptInviteError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, invite.ErrInviteInvalid):
http.Error(w, apperr.InviteInvalidErrorMessage, http.StatusNotFound)
case errors.Is(err, invite.ErrInviteExpired):
http.Error(w, apperr.InviteExpiredErrorMessage, http.StatusGone)
case errors.Is(err, user.ErrUsernameTaken):
http.Error(w, apperr.UsernameTakenErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrEmailHasAccount):
http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
+8 -4
View File
@@ -52,22 +52,26 @@ func removeJwtCookie(w http.ResponseWriter, isProduction bool) {
})
}
func (h *LoginHandler) SetJwtCookie(w *http.ResponseWriter, u user.User) error {
_, tokenString, err := h.Token.Encode(map[string]any{"user_id": u.ID, "token_version": u.TokenVersion})
func setJwtCookie(w http.ResponseWriter, token *jwtauth.JWTAuth, isProduction bool, u user.User) error {
_, tokenString, err := token.Encode(map[string]any{"user_id": u.ID, "token_version": u.TokenVersion})
if err != nil {
return err
}
http.SetCookie(*w, &http.Cookie{
http.SetCookie(w, &http.Cookie{
Name: "jwt",
Value: tokenString,
Expires: time.Now().Add(24 * time.Hour),
Secure: h.IsProduction,
Secure: isProduction,
HttpOnly: true,
Path: "/",
})
return nil
}
func (h *LoginHandler) SetJwtCookie(w *http.ResponseWriter, u user.User) error {
return setJwtCookie(*w, h.Token, h.IsProduction, u)
}
func (h *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
var credentials LoginCredentials
+2 -1
View File
@@ -3,6 +3,7 @@ package auth
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/publicuser"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
@@ -37,7 +38,7 @@ func (h *MeHandler) Me(w http.ResponseWriter, r *http.Request) {
return
}
body, err := json.Marshal(newPublicUser(loadedUser))
body, err := json.Marshal(publicuser.New(loadedUser))
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
+2 -22
View File
@@ -3,13 +3,13 @@ package auth
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/publicuser"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"time"
)
type VerificationHandler struct {
@@ -22,26 +22,6 @@ type VerifyCredentials struct {
Code string `json:"code" validate:"required"`
}
type PublicUser struct {
ID uint32 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
IsVerified bool `json:"is_verified"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func newPublicUser(u user.User) PublicUser {
return PublicUser{
ID: u.ID,
Username: u.Username,
Email: u.Email,
IsVerified: u.IsVerified,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
}
}
func NewVerificationHandler(verify *useCases.VerifyUserUseCase, cancel *useCases.CancelRegistrationUseCase, isProduction bool) *VerificationHandler {
return &VerificationHandler{
VerifyUseCase: verify,
@@ -84,7 +64,7 @@ func (h *VerificationHandler) Verify(w http.ResponseWriter, r *http.Request) {
return
}
body, err := json.Marshal(newPublicUser(verifiedUser))
body, err := json.Marshal(publicuser.New(verifiedUser))
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
+34 -2
View File
@@ -17,13 +17,15 @@ type Handler struct {
CreateUseCase *useCases.CreateImageUseCase
GetUseCase *useCases.GetArticleUseCase
UpdateUseCase *useCases.UpdateArticleUseCase
DeleteUseCase *useCases.DeleteImageUseCase
}
func NewHandler(create *useCases.CreateImageUseCase, get *useCases.GetArticleUseCase, update *useCases.UpdateArticleUseCase) *Handler {
func NewHandler(create *useCases.CreateImageUseCase, get *useCases.GetArticleUseCase, update *useCases.UpdateArticleUseCase, deleteUseCase *useCases.DeleteImageUseCase) *Handler {
return &Handler{
CreateUseCase: create,
GetUseCase: get,
UpdateUseCase: update,
DeleteUseCase: deleteUseCase,
}
}
@@ -78,7 +80,7 @@ func (h *Handler) PostImage(w http.ResponseWriter, r *http.Request) {
return
}
responseJson, err := json.Marshal(map[string]any{"location": newImage.Path})
responseJson, err := json.Marshal(map[string]any{"id": newImage.ID, "location": newImage.Path})
if err != nil {
writeInternalServerError(w)
return
@@ -87,3 +89,33 @@ func (h *Handler) PostImage(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
_, _ = w.Write(responseJson)
}
func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) {
articleId, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
imageId, err := strconv.ParseUint(chi.URLParam(r, "imageId"), 10, 32)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
if _, err := h.GetUseCase.GetArticle(uint32(articleId)); err != nil {
writeArticleError(w, err)
return
}
if err := h.DeleteUseCase.DeleteImage(uint32(imageId)); err != nil {
if errors.Is(err, domainImage.ErrImageNotFound) {
http.Error(w, apperr.ImageNotFoundErrorMessage, http.StatusNotFound)
return
}
writeInternalServerError(w)
return
}
w.WriteHeader(http.StatusNoContent)
}
+24
View File
@@ -0,0 +1,24 @@
package settings
import (
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"net/http"
)
type Handler struct {
GetSettingsUseCase *useCases.GetSettingsUseCase
}
func NewHandler(getSettings *useCases.GetSettingsUseCase) *Handler {
return &Handler{GetSettingsUseCase: getSettings}
}
func (h *Handler) GetSettings(w http.ResponseWriter, _ *http.Request) {
body, err := json.Marshal(h.GetSettingsUseCase.GetSettings())
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
_, _ = w.Write(body)
}
+204
View File
@@ -0,0 +1,204 @@
package user
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/invite"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi/v5"
)
type InviteHandler struct {
CreateInviteUseCase *useCases.CreateInviteUseCase
CancelInviteUseCase *useCases.CancelInviteUseCase
RenewInviteUseCase *useCases.RenewInviteUseCase
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
}
type CreateInviteRequest struct {
Email string `json:"email" validate:"required,inviteemail"`
}
type inviteResponse struct {
ID uint32 `json:"id"`
Kind string `json:"kind"`
Email string `json:"email"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
type inviteListItem struct {
ID uint32 `json:"id"`
Kind string `json:"kind"`
Email string `json:"email"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
type userListItem struct {
ID uint32 `json:"id"`
Kind string `json:"kind"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
Email string `json:"email"`
Role string `json:"role"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
func NewInviteHandler(createInvite *useCases.CreateInviteUseCase, cancelInvite *useCases.CancelInviteUseCase, renewInvite *useCases.RenewInviteUseCase, listUsersAndInvites *useCases.ListUsersAndInvitesUseCase) *InviteHandler {
return &InviteHandler{
CreateInviteUseCase: createInvite,
CancelInviteUseCase: cancelInvite,
RenewInviteUseCase: renewInvite,
ListUsersAndInvitesUseCase: listUsersAndInvites,
}
}
func (h *InviteHandler) CreateInvite(w http.ResponseWriter, r *http.Request) {
var request CreateInviteRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
created, err := h.CreateInviteUseCase.CreateInvite(useCases.CreateInviteCommand{
Email: request.Email,
InvitedBy: userId,
})
if err != nil {
writeCreateInviteError(w, err)
return
}
writeInviteResponse(w, http.StatusCreated, created)
}
func writeInviteResponse(w http.ResponseWriter, status int, entry invite.Invite) {
body, err := json.Marshal(inviteResponse{
ID: entry.ID,
Kind: useCases.EntryKindInvite,
Email: entry.Email,
Status: string(entry.StatusAt(time.Now())),
CreatedAt: entry.CreatedAt,
ExpiresAt: entry.ExpiresAt,
})
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_, _ = w.Write(body)
}
func parseInviteId(r *http.Request) (uint32, error) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
return uint32(id), err
}
func (h *InviteHandler) CancelInvite(w http.ResponseWriter, r *http.Request) {
id, err := parseInviteId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
if err := h.CancelInviteUseCase.CancelInvite(id); err != nil {
writeManageInviteError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *InviteHandler) RenewInvite(w http.ResponseWriter, r *http.Request) {
id, err := parseInviteId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
renewed, err := h.RenewInviteUseCase.RenewInvite(useCases.RenewInviteCommand{ID: id, RenewedBy: userId})
if err != nil {
writeManageInviteError(w, err)
return
}
writeInviteResponse(w, http.StatusOK, renewed)
}
func writeManageInviteError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, invite.ErrInviteNotFound):
http.Error(w, apperr.InviteNotFoundErrorMessage, http.StatusNotFound)
case errors.Is(err, invite.ErrInviteAlreadyAccepted):
http.Error(w, apperr.InviteAlreadyAcceptedErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrInviteEmailNotSent):
http.Error(w, apperr.InviteNotSentErrorMessage, http.StatusInternalServerError)
case errors.Is(err, user.ErrUserNotFound):
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func writeCreateInviteError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, invite.ErrEmailHasAccount):
http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrPendingInvite):
http.Error(w, apperr.PendingInviteErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrInviteEmailNotSent):
http.Error(w, apperr.InviteNotSentErrorMessage, http.StatusInternalServerError)
case errors.Is(err, user.ErrUserNotFound):
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func (h *InviteHandler) ListUsers(w http.ResponseWriter, _ *http.Request) {
entries := h.ListUsersAndInvitesUseCase.ListUsersAndInvites()
items := make([]any, 0, len(entries))
for _, entry := range entries {
if entry.Kind == useCases.EntryKindInvite {
items = append(items, inviteListItem{entry.ID, entry.Kind, entry.Email, entry.Status, entry.CreatedAt})
continue
}
items = append(items, userListItem{entry.ID, entry.Kind, entry.Username, entry.DisplayName, entry.Email, entry.Role, entry.Status, entry.CreatedAt})
}
body, err := json.Marshal(items)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
+70
View File
@@ -0,0 +1,70 @@
package user
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/publicuser"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
)
type Handler struct {
UpdateProfileUseCase *useCases.UpdateUserProfileUseCase
}
type UpdateProfileRequest struct {
DisplayName *string `json:"display_name" validate:"required"`
}
func NewHandler(updateProfile *useCases.UpdateUserProfileUseCase) *Handler {
return &Handler{
UpdateProfileUseCase: updateProfile,
}
}
func (h *Handler) UpdateMe(w http.ResponseWriter, r *http.Request) {
var request UpdateProfileRequest
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
err = validator.Validate.Struct(request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
updatedUser, err := h.UpdateProfileUseCase.UpdateDisplayName(userId, *request.DisplayName)
if err != nil {
if errors.Is(err, user.ErrInvalidDisplayName) {
http.Error(w, apperr.DisplayNameErrorMessage, http.StatusBadRequest)
return
}
if errors.Is(err, user.ErrUserNotFound) {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
body, err := json.Marshal(publicuser.New(updatedUser))
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
+18
View File
@@ -77,3 +77,21 @@ func RequireVerifiedUser(getUser *useCases.GetUserUseCase) func(http.Handler) ht
})
}
}
func RequireOwner(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
currentUser, ok := resolveCurrentUser(getUser, w, r)
if !ok {
return
}
if currentUser.Role != user.RoleOwner {
http.Error(w, apperr.OwnerRequiredErrorMessage, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}
+11
View File
@@ -4,6 +4,8 @@ const LogsErrorMessage = "Access to the requested resource is forbidden due to i
const BodyErrorMessage = "The request cannot be processed due to a mismatch in the format of the body."
const IdUint32ErrorMessage = "The server expects the ID to be in the format of an unsigned 32-bit integer (uint32)."
const ArticleNotFoundErrorMessage = "Article not found"
const ImageNotFoundErrorMessage = "Image not found"
const DisplayNameErrorMessage = "Display name must be 60 characters or fewer."
const ArticleTitleErrorMessage = "Article title must be between 3 and 200 characters."
const RegistrationClosedErrorMessage = "You are not allowed to create a user. Log in or reset database."
const RegistrationFailedErrorMessage = "Registration failed. Please try again later."
@@ -14,3 +16,12 @@ const VerificationRequiredErrorMessage = "You must verify your account to access
const PasswordResetRequestedMessage = "If an account exists for that email, a password reset link has been sent."
const PasswordResetFailedErrorMessage = "The password reset code is invalid or has expired."
const TooManyRequestsErrorMessage = "Too many requests. Please try again later."
const EmailHasAccountErrorMessage = "This address already has an account."
const PendingInviteErrorMessage = "There's already a pending invite for this address."
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
const InviteNotFoundErrorMessage = "Invite not found"
const InviteAlreadyAcceptedErrorMessage = "This invite has already been accepted."
const InviteInvalidErrorMessage = "This invite link doesn't work."
const InviteExpiredErrorMessage = "This invite has expired."
const OwnerRequiredErrorMessage = "Only the owner can do this."
const UsernameTakenErrorMessage = "That username is taken. Try another."
+30
View File
@@ -0,0 +1,30 @@
package publicuser
import (
"RenewCMS/internal/domain/user"
"time"
)
type PublicUser struct {
ID uint32 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
IsVerified bool `json:"is_verified"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DisplayName string `json:"display_name"`
Role user.Role `json:"role"`
}
func New(u user.User) PublicUser {
return PublicUser{
ID: u.ID,
Username: u.Username,
Email: u.Email,
IsVerified: u.IsVerified,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
DisplayName: u.DisplayName,
Role: u.Role,
}
}
+14 -1
View File
@@ -1,9 +1,22 @@
package validator
import "github.com/go-playground/validator/v10"
import (
"regexp"
"github.com/go-playground/validator/v10"
)
const inviteEmailTag = "inviteemail"
var inviteEmailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$`)
var Validate *validator.Validate
func InitValidator() {
Validate = validator.New()
_ = Validate.RegisterValidation(inviteEmailTag, isInviteEmail)
}
func isInviteEmail(field validator.FieldLevel) bool {
return inviteEmailPattern.MatchString(field.Field().String())
}
+49 -1
View File
@@ -5,7 +5,9 @@ import (
"RenewCMS/api/handlers/auth"
"RenewCMS/api/handlers/frontend"
"RenewCMS/api/handlers/image"
"RenewCMS/api/handlers/settings"
"RenewCMS/api/handlers/staticimages"
"RenewCMS/api/handlers/user"
"RenewCMS/api/middleware"
"RenewCMS/internal/infrastructure/config"
"encoding/json"
@@ -33,7 +35,7 @@ func NewArticleRouter(container *UseCases) http.Handler {
r := chi.NewRouter()
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase)
imageHandler := image.NewHandler(container.CreateImageUseCase, container.GetArticleUseCase, container.UpdateArticleUseCase)
imageHandler := image.NewHandler(container.CreateImageUseCase, container.GetArticleUseCase, container.UpdateArticleUseCase, container.DeleteImageUseCase)
r.Group(func(r chi.Router) {
r.Get("/", articleHandler.ListArticles)
@@ -49,6 +51,7 @@ func NewArticleRouter(container *UseCases) http.Handler {
r.Patch("/{id}/publish", articleHandler.PublishArticle)
r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle)
r.Post("/{id}/image", imageHandler.PostImage)
r.Delete("/{id}/image/{imageId}", imageHandler.DeleteImage)
})
return r
}
@@ -60,6 +63,7 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
verificationHandler := auth.NewVerificationHandler(container.VerifyUserUseCase, container.CancelRegistrationUseCase, isProduction)
meHandler := auth.NewMeHandler(container.GetUserUseCase)
passwordResetHandler := auth.NewPasswordResetHandler(container.RequestPasswordResetUseCase, container.ResetPasswordUseCase)
acceptInviteHandler := auth.NewAcceptInviteHandler(container.GetInviteUseCase, container.AcceptInviteUseCase, container.Token, isProduction)
r.Post("/register", loginHandler.Register)
r.Get("/registration", loginHandler.RegistrationStatus)
@@ -75,6 +79,12 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
r.Post("/password-reset", passwordResetHandler.RequestPasswordReset)
})
r.Post("/password-reset/confirm", passwordResetHandler.ResetPassword)
r.Group(func(r chi.Router) {
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
r.Get("/invite", acceptInviteHandler.GetInvite)
r.Post("/invite/accept", acceptInviteHandler.AcceptInvite)
})
r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token))
@@ -86,6 +96,42 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
return r
}
func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler {
r := chi.NewRouter()
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase)
r.Use(jwtauth.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token))
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Patch("/me", userHandler.UpdateMe)
r.Get("/", inviteHandler.ListUsers)
r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase))
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
r.Post("/invite", inviteHandler.CreateInvite)
r.Delete("/invite/{id}", inviteHandler.CancelInvite)
r.Post("/invite/{id}/renew", inviteHandler.RenewInvite)
})
return r
}
func NewSettingsRouter(container *UseCases) http.Handler {
r := chi.NewRouter()
settingsHandler := settings.NewHandler(container.GetSettingsUseCase)
r.Use(jwtauth.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token))
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", settingsHandler.GetSettings)
return r
}
func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
r := chi.NewRouter()
@@ -98,6 +144,8 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
r.Use(jwtauth.Verifier(container.Token))
r.Mount("/article", NewArticleRouter(container))
})
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
r.Mount("/settings", NewSettingsRouter(container))
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
return r
+1
View File
@@ -62,6 +62,7 @@ func run() error {
if err != nil {
return err
}
settings.Version = version
container, closeDb := api.InitContainer(settings)
defer closeDatabase(closeDb)
+7
View File
@@ -21,6 +21,13 @@ api/ ──▶ internal/infrastructure/useCases ──▶ internal/domain
Nothing under `internal/` imports `api/`.
### Delivery packages
| Package | Role |
|---|---|
| `api/handlers/user` | Authenticated user endpoints: profile update (`UpdateMe`) and the users list with invitations (`CreateInvite`, `ListUsers`). |
| `api/pkg/publicuser` | `PublicUser`, the JSON shape of a user with no password, codes or token version. `publicuser.New` converts a domain `user.User`, so handlers never serialise the domain struct directly. |
## Frontend ↔ backend
```
+3 -3
View File
@@ -27,9 +27,9 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
| `DB_FILE` | `./data/renewcms.db` | Path to the SQLite database file. Missing parent directories are created. The schema is migrated automatically at startup. |
| `UPLOAD_DIR` | `./data/uploads` | Directory where uploaded images are stored. |
| `CORS_ALLOWED_ORIGINS` | *(empty)* | Semicolon-separated list of origins allowed to call the API. When empty, no CORS headers are sent. That is the right setting whenever the SPA is served by RenewCMS itself (production) or through the Vite proxy (development). |
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login` or `POST /v1/auth/password-reset` within the window, tracked independently per route. |
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the two routes above. |
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for `POST /v1/auth/login` and `POST /v1/auth/password-reset` rate limiting. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. |
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
Relative paths are resolved against the process's working directory. In production, use absolute paths (see [deployment.md](deployment.md)).
+8 -3
View File
@@ -11,7 +11,7 @@ The visual spec of record for the back-office SPA and the transactional emails,
| `states.md` | Every state of every screen with its trigger, and the HTTP-status-to-copy table |
| `screens/<screen>.md` | One file per screen: route, API, and per state the exact copy, fields, alerts, dialogs and toasts |
| `foundations.md` | Colors, contrast, type, spacing, motion and icons, and where the token files are |
| `emails.md` | The two email templates and their variables |
| `emails.md` | The three email templates and their variables |
| `source/` | The raw Claude Design export. Open the `.dc.html` boards in a browser for the drawings (they load `support.js` locally and fonts from Google). |
## Screens
@@ -28,12 +28,17 @@ The visual spec of record for the back-office SPA and the transactional emails,
| [Home](screens/home.md) | `/home` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
| [Articles](screens/articles.md) | `/article` | 14 | `source/RenewCMS Screens Back-office.dc.html` |
| [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` |
| [Editor](screens/editor.md) | `/article/:id/edit` | 19 | `source/RenewCMS Screens Back-office.dc.html` |
| [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
| [Users](screens/users.md) | `/users` | 17 | `source/RenewCMS Screens Back-office.dc.html` |
| [Settings](screens/settings.md) | `/settings` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
| [Profile](screens/profile.md) | `/profile` | 13 | `source/RenewCMS Screens Back-office.dc.html` |
| [Accept invite](screens/accept-invite.md) | `/invite/accept?c=CODE` | 9 | `source/RenewCMS Screens Auth.dc.html` |
| [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
## Other boards
- `source/RenewCMS Prototype.dc.html`: the clickable flows (first run, edit and publish, password reset, delete, session expiry mid-edit).
- `source/RenewCMS Handoff.dc.html`: the handoff page the markdown here was generated from.
- `source/RenewCMS Handoff.dc.html`: the handoff page the first markdown here was generated from. It predates the Users and Profile screens and the invitation email, so it does not list them. Those are written by hand from the Back-office board, `AppFrame.dc.html`, the Prototype and `emails/invitation.html`.
- `source/RenewCMS Components Product.dc.html`: not regenerated for the new screens either. The matching component changes are in `components.md`, under "Added with the Users and Profile screens" and "Added with roles, invite actions and Settings".
- `source/RenewCMS Directions.dc.html`: the three brand directions (history only).
+107 -10
View File
@@ -6,7 +6,14 @@
|---|---|---|---|---|---|
| AuthShell | UPageCard, UColorModeSelect | title, description? | none | default, notice, footer | All public routes |
| DashboardShell | UDashboardGroup, UDashboardSidebar, UNavigationMenu, UDashboardPanel, UDashboardNavbar, UBreadcrumb | none (reads route.meta and the session store) | none | default, navbar-right | All verified routes |
| UserMenu | UDropdownMenu, UButton, UAvatar | none | logout | none | DashboardShell |
| UserMenu | UDropdownMenu, UButton, UAvatar (a bottom sheet below md) | displayName?, username, email | logout | none | DashboardShell |
| UsersTable | UTable | rows: UserRow[], loading, canManage: boolean, busyIds: Set | cancel-invite, renew-invite | none | Users (md and up) |
| UserCardList | custom list | same as UsersTable | same as UsersTable | none | Users (below md) |
| RoleBadge | UBadge | role: 'owner'\|'admin' | none | none | Users |
| SettingsPage | custom card | none (reads GET /v1/settings) | none | none | Settings |
| InviteStatusBadge | UBadge | status: 'accepted'\|'pending'\|'expired' | none | none | Users |
| InviteUserModal | UModal, UForm, UFormField, UInput | none | invited(invite) | none | Users |
| ProfileCard | custom card (border, padding, optional footer strip) | title, description | none | default, footer | Profile |
| PageHeader | UPageHeader | title, description? | none | actions, meta | Home, Articles, Integration |
| ArticleStatusBadge | UBadge | online: boolean, size?: 'sm'\|'md', pending?: 'publish'\|'unpublish' | none | none | Home, Articles, Editor |
| ArticleTable | UTabs, UInput, UTable, UDropdownMenu, UPagination | articles: Article[], loading, busyIds: Set<number> | publish, unpublish, delete, copy-url | empty, toolbar-right | Articles (md and up) |
@@ -19,16 +26,16 @@
| SaveStatus | custom (span + UButton) | state: 'clean'\|'dirty'\|'saving'\|'saved'\|'error'\|'offline', savedAt?: Date | retry | none | Editor |
| PublishControl | UButton | online: boolean, dirty: boolean, pending?: string, disabled? | publish, unpublish | none | Editor |
| ArticleDetails | UCard (desktop) / USlideover (mobile) | article: Article | copy-url | none | Editor |
| CharacterCounter | custom | value: number, max: number, min?: number, warnAt?: number | none | none | NewArticleModal, Editor, Register |
| PasswordStrengthHint | custom (in UFormField #help) | rules: { label, met }[], showErrors: boolean | none | none | Register, Reset |
| ResultPanel | custom + UButton | tone: 'success'\|'error'\|'info', icon, title, description, actions: ButtonProps[] | none | default | Pending, Verify, Reset request, Reset, Register (403) |
| CharacterCounter | custom | value: number, max: number, min?: number, warnAt?: number | none | none | NewArticleModal, Editor, Register, Accept invite |
| PasswordStrengthHint | custom (in UFormField #help) | rules: { label, met }[], showErrors: boolean | none | none | Register, Reset, Accept invite |
| ResultPanel | custom + UButton | tone: 'success'\|'error'\|'info', icon, title, description, actions: ButtonProps[] | none | default | Pending, Verify, Reset request, Reset, Accept invite, Register (403) |
| CodeBlock | custom (shiki) + UButton | code: string, lang: string, label? | none | none | Integration |
| EndpointCard | UCard, UBadge, UTabs | method: 'GET', path, description, examples: { fetch, curl, response } | none | none | Integration |
| ErrorView | custom + UButton | kind: 'not-found'\|'error' | retry | none | Not found, error boundary |
| OfflineBanner | UBanner | none (reads useOnline) | none | none | DashboardShell |
| AppBoot | USkeleton inside DashboardShell | none | none | none | First load of any verified route |
Composables behind these components: `useSession`, `useApi`, `useArticles` (the list cache plus actions shared by the table, cards and editor), `useArticleDraft` (dirty state, save, and the sessionStorage mirror), `useImageUpload` (XHR with progress) and `useRetryAfter` (429 countdown).
Composables behind these components: `useSession` (it also carries the display name), `useUsers` (the list and the invite action), `useProfile` (the display name draft and save), `useApi`, `useArticles` (the list cache plus actions shared by the table, cards and editor), `useArticleDraft` (dirty state, save, and the sessionStorage mirror), `useImageUpload` (XHR with progress) and `useRetryAfter` (429 countdown).
## Product component specs
@@ -58,7 +65,7 @@ Responsive 400 px card from sm up, with its top 12 vh from the top. Below sm , t
### DashboardShell
The sidebar has three destinations, and the user menu sits at its foot. The top bar carries the breadcrumbs and page title. Collapsing the sidebar leaves a 56 px icon rail. Below lg , the sidebar becomes a slideover.
The sidebar has five destinations (Home, Articles, Users, Integration, Settings), and the user menu sits at its foot. The top bar carries the breadcrumbs and page title. Collapsing the sidebar leaves a 56 px icon rail. Below lg , the sidebar becomes a slideover.
RenewCMS
@@ -92,7 +99,7 @@ Mobile top bar. The menu button opens the sidebar as a left slideover.
Built from UDashboardGroup storage="local" › UDashboardSidebar collapsible :resizable="false" :default-size="16" :collapsed-size="4" with the #header (AppLogo), #default ( UNavigationMenu orientation="vertical" :collapsed ) and #footer (UserMenu) slots. Each page is a UDashboardPanel , with a UDashboardNavbar holding UDashboardSidebarCollapse and UBreadcrumb . On mobile, UDashboardSidebarToggle appears and the sidebar's built-in slideover takes over.
UserMenu UDropdownMenu :content="{ side: 'top', align: 'start' }" on a ghost UButton block with a UAvatar and the username. The groups are: the account label; System, Light and Dark as checkbox items; then Log out. There are no profile or password items, because the API doesn't support them.
UserMenu UDropdownMenu :content="{ side: 'top', align: 'start' }" on a ghost UButton block with a UAvatar and the username. The groups are: the account label; System, Light and Dark as checkbox items; then Log out. There are no profile or password items, because the API doesn't support them. Superseded: see "UserMenu (changed)" under "Added with the Users and Profile screens", which restores the System, Light and Dark items.
Props, slots No props, because the shell reads the user from the session Pinia store. The navbar reads route.meta.title and route.meta.breadcrumb . Slots navbar-right (page actions on mobile) and default . It shows the offline banner when navigator.onLine is false.
@@ -252,7 +259,7 @@ Responsive Below lg , the details panel becomes a right slideover, opened with i
### ImageUploader
Opens from the editor's image button in a small modal. Files are checked in the browser before anything is sent. After a successful upload the image goes in at the cursor and the modal closes.
Opens from the editor's image button in a small modal. Files are checked in the browser before anything is sent. A JPEG, PNG or WEBP then goes through a crop-and-resize step before it uploads; an SVG skips straight to uploading. After a successful upload the image goes in at the cursor and the modal closes.
Drop an image here Choose file PNG, JPEG, WEBP, SVG · max 10 MB
@@ -262,9 +269,21 @@ Drop to upload
dragging over
north-wall.jpg 62%
Crop and resize north-wall.jpg · 3.9 MB
Uploading 2.4 of 3.9 MB
crop, default: whole image selected, width "1600 px"
Crop and resize north-wall.jpg · 3.9 MB
crop, ratio locked to 16:9
Crop and resize north-wall.jpg · 3.9 MB
crop, crop narrower than the chosen width
north-wall.jpg 43%
Uploading 180 of 420 KB
uploading
@@ -282,6 +301,10 @@ server error
Built from UModal title="Add an image" › UFileUpload accept="image/png,image/jpeg,image/webp,image/svg+xml" :multiple="false" layout="list" + UProgress size="xs" . Uploads go through XMLHttpRequest , because fetch has no upload progress, as FormData with the field name file . The 201 location is inserted with insertImage(location, '') .
Crop and resize A JPEG, PNG or WEBP opens on a 640px-wide modal (`md.crop`) between the file picker and the upload, replacing the "Add an image" title with "Crop and resize" and the filename/size as the description. The stage shows the image with the crop frame starting as the whole image: a rule-of-thirds grid (lines at 33.3 %/66.6 %), four 12×12 px corner handles, and a pixel-size label (mono, bottom-left, dark pill) that tracks the frame's current size. The frame is `tabindex="0"`, `aria-label="Crop area. Arrow keys move it, Shift and arrow keys resize it."`; dragging moves it, dragging a handle resizes it, arrow keys nudge it by 1 px and Shift+arrow keys resize it.
Aspect ratio is a `radiogroup` of five pills — Original, Free, 16:9, 4:3, 1:1 — plus Rotate and Reset actions above it. Width is a second `radiogroup` — Original, 1600 px (default), 1200 px, 800 px. A mono line below reads "Uploads as {width} × {height} px · about {size}", where the estimated size is shown in KB under 1 MB and in MB above it. When the chosen width is larger than the crop's own width, the output stays at the crop's size (never upscaled) and an info row explains why: "The crop is {crop width} px wide, so it's uploaded at that size. Enlarging it would make it blurry." The footer becomes "Choose another file" (back to the file picker, `data-act="upload-pick"` from `idle`) and "Upload image" (starts the upload with the cropped, resized file). SVGs never see this step: they upload as soon as they're chosen. The "in progress" state afterwards reports the resized file's size, e.g. "Uploading 180 of 420 KB".
Validation Before uploading, the uploader checks both the MIME type and the file extension, and that size ≤ 10 × 1024 × 1024 . The size error names the file size: "north-wall.tif is 14.2 MB. Images can be up to 10 MB." A server 400 shows the same message as a client-side rejection.
Props, emits articleId: number . Emits uploaded(location) , close . A 401 hands off to the global session flow. A 404 means the article was deleted, which the editor handles.
@@ -354,6 +377,51 @@ Built from UError isn't used because it's built for Nuxt's error.vue . Instead t
A11y The error title is the page h1 and gets focus on render. The banner is role="status" , and it can't be dismissed while offline. The offline state blocks Save and Publish and says why in their tooltip.
## Added with the Users and Profile screens
The Product components board was not regenerated for these. They are written from `source/RenewCMS Screens Back-office.dc.html`, `source/AppFrame.dc.html` and the Prototype. Their exact values come from AppFrame.
### UserMenu (changed)
The chip at the foot of the sidebar no longer logs out on click. It opens the account menu, which lists Profile, the theme choice and Log out.
- **Chip:** 40 px high, an initials avatar (26 px, sand `#d4c5b0` with ink text), the name, and a chevrons-up-down icon. `aria-haspopup="menu"`, `aria-expanded`, title "Account". While the menu is open, or while `/profile` is the current page, it takes `--rc-sand` with `#111111` text.
- **Name:** the display name when there is one, otherwise the username. Initials come from the first letters of the first two words of the display name, uppercased. Without a display name they come from the username.
- **Desktop menu:** a 224 px popover anchored above the chip on its left edge, with `--rc-shadow-pop`. Header: the name in semibold, the email below it in muted 12 px, a bottom border. Items are 32 px: Profile (circle-user), a separator, System, Light and Dark (14 px text, a check icon at the right edge on the current choice), a separator, Log out (log-out). The current page's item is highlighted with `--ui-bg-elevated`. The theme items are radio-style: choosing one applies at once and keeps the menu open. Nuxt UI: `type: 'checkbox'` items bound to `useColorMode().preference`.
- **Mobile:** the account row in the navigation drawer opens a bottom sheet over an `--rc-overlay` scrim, with a grab handle. Header: 36 px avatar, name in 15 px semibold, email in muted text. Items are 48 px at 15 px text; the theme items keep the same order and separators.
- **Keyboard:** Escape or a click outside closes it. Arrow keys move between items.
- The board now draws the theme items, so the chip, menu and sheet need no visual exception. The board highlights Profile even on Home; the app highlights it only on `/profile`.
### DashboardShell (changed)
The navigation gains **Users** (users icon) between Articles and Integration, in the sidebar and in the mobile drawer. Breadcrumbs for the new pages are "Users" and "Profile". It later gains **Settings** (settings icon) after Integration, with the breadcrumb "Settings".
### UsersTable, UserCardList
Superseded by "UsersTable, UserCardList (changed)" below.
Skeleton rows appear after 150 ms of loading.
### InviteStatusBadge
A 22 px outline-less badge with a 12 px icon and the word, so status is never shown by color alone.
| Status | Icon | Fill and text |
|---|---|---|
| Accepted | circle-check | `--rc-success-soft`, `--ui-success` |
| Pending | mail | `--rc-warning-soft`, `--ui-warning` |
| Expired | clock-alert | transparent, `--ui-text-muted`, border `--ui-border-accented` |
### InviteUserModal
A UModal with one field, following the NewArticleModal pattern: title "Invite a user", the text "We'll email them a link to choose a username and password. The link expires after 3 days.", an Email field (placeholder "name@example.com", focused on open), Cancel and "Send invite". While sending, the field is disabled, the button reads "Sending…" and the dialog can't be dismissed. A field error shows under the input, a request failure shows an alert above the buttons, and the address always stays in the field. On success it closes and emits the new invite.
### ProfileCard
A bordered card with 20 px padding (16 px on mobile), a semibold 14 px title, a muted description, and its content. An optional footer strip sits below a top border on `--ui-bg-muted`, with the status text on the left and the action on the right. The Display name card uses the footer; Account and Password do not.
The Display name field uses CharacterCounter with a maximum of 60, counted in Unicode characters, in the mono style on the right of the help row. Read-only fields (username, email, password) are disabled inputs on `--ui-bg-elevated` with a lock icon at the right.
## Themed primitives
Extracted from `source/RenewCMS Components Primitives.dc.html`.
@@ -667,3 +735,32 @@ Three choices: System (the default), Light and Dark. The toggle at the top of th
Nuxt UI In the user menu: a UDropdownMenu group of three type: 'checkbox' items bound to useColorMode().preference . On auth screens: UColorModeSelect in the footer. Nuxt UI's UColorModeButton isn't used because it only toggles between light and dark and hides the system option. colorMode: true in the plugin handles storage and applying the .dark class before first paint.
ARIA Menu items use menuitemcheckbox , with aria-checked on the current choice. The segmented variant is a radiogroup named "Theme".
## Added with roles, invite actions and Settings
Written from `source/RenewCMS Screens Back-office.dc.html` and `source/AppFrame.dc.html`. The Product components board was not regenerated for these.
### UsersTable, UserCardList (changed)
Columns Email, Display name, Role, Invite status, Created (sorted descending, with an arrow-down icon on the header) and an unlabeled actions column. Grid `minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px`, 12 px gap, 36 px header on `--ui-bg-elevated`, 48 px rows with a top border. Below md the same rows become cards with a 68 px minimum height: the email line, the display name below it when set, then role badge, status badge and "Created {date}" on one line, then the row action as a 44 px button.
The email cell is medium weight and highlighted, with a mono "you" tag on the current user's row. The display name is highlighted, or a muted `—` when empty. The row of a just-sent or just-renewed invite has `--ui-bg-elevated`. Skeleton rows have one bar per column. The username is not shown.
### RoleBadge
A 20 px badge in IBM Plex Mono 11 px medium, 7 px side padding, no icon.
| Role | Fill | Text | Border |
|---|---|---|---|
| owner | `--ui-primary` | `--ui-bg` | `--ui-primary` |
| admin | transparent | `--ui-text-toned` | `--ui-border-accented` |
### Row action button (Users)
A 28 px outline button on desktop (12 px medium text, 13 px icon, 9 px side padding, `--ui-border-accented` border, `--ui-bg` fill, no wrapping), 44 px on mobile (14 px side padding, 14 px icon). Cancel invite: user-x, text `--ui-error`. Renew invite: refresh-cw, text `--ui-text-highlighted`. While busy: the label becomes "Renewing…", the icon loader-circle, opacity 50 %, disabled. Nuxt UI: `UButton variant="outline" size="xs"` with the classes above.
Cancel goes through `ConfirmDialog` with `tone: 'danger'`: title "Cancel this invite?", the description names the address, the cancel button reads "Keep invite" and the confirm button "Cancel invite", pending label "Cancelling…", and a failure shows a notice inside the dialog.
### SettingsPage
A page header (title "Settings", subtitle "Workspace information."), then one card holding a "Version" row. See [screens/settings.md](screens/settings.md).
+4 -2
View File
@@ -5,10 +5,12 @@ Go `html/template` files, ready to replace `internal/infrastructure/mailer/templ
- `source/emails/verification.html` uses `{{.Host}}` and `{{.VerificationCode}}`, linking to `{{.Host}}/register/validate?c={{.VerificationCode}}`.
- `source/emails/password-reset.html` uses `{{.Host}}`, `{{.VerificationCode}}` and `{{.Email}}`, linking to `{{.Host}}/register/reset/validate?c={{.VerificationCode}}&email={{.Email}}`.
- `source/emails/invitation.html` uses `{{.Host}}`, `{{.VerificationCode}}`, `{{.Email}}` and `{{.InvitedBy}}`, linking to `{{.Host}}/invite/accept?c={{.VerificationCode}}`. `{{.Email}}` is the invited address, shown in the body only. `{{.InvitedBy}}` is the inviter's display name, or their username when they have none. The subject is "{{.InvitedBy}} invited you to RenewCMS". The invite expires in 3 days and works once.
Previews: `source/RenewCMS Emails.dc.html`.
## Transactional emails
Two Go html/template files: emails/verification.html and emails/password-reset.html . They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and prefers-color-scheme overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values.
Three Go html/template files: emails/verification.html, emails/password-reset.html and emails/invitation.html . They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and prefers-color-scheme overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values.
Suggested subjects are "Verify your RenewCMS account" and "Reset your RenewCMS password". html/template escapes the .Email value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded.
Suggested subjects are "Verify your RenewCMS account", "Reset your RenewCMS password" and "<InvitedBy> invited you to RenewCMS", where .InvitedBy is the inviter's display name or username. html/template escapes the .Email value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded.
+4
View File
@@ -16,6 +16,10 @@ A global `router.beforeEach` guard reads `meta.auth`. On the first navigation it
| `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ |
| `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · POST /{id}/image · DELETE /{id} |
| `/integration` | DashboardShell | verified | IntegrationPage | none |
| `/users` | DashboardShell | verified | UsersPage + InviteUserModal | GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id · POST /v1/user/invite/:id/renew |
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings |
| `/profile` | DashboardShell | verified | ProfilePage | GET /v1/auth/me · PATCH /v1/user/me · POST /v1/auth/password-reset |
| `/invite/accept` | AuthShell | public | AcceptInvitePage | GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept* |
| `/:pathMatch(.*)*` | either | any | NotFoundPage | none |
Auth values: `public` needs no session, `session` needs a logged-in account (verified or not), `verified` needs a verified account, `any` applies to redirects and the catch-all.
+114
View File
@@ -0,0 +1,114 @@
# Accept invite
- **Route:** `/invite/accept?c=CODE`
- **API:** GET /v1/auth/invite?c=CODE (pending) · POST /v1/auth/invite/accept (pending)
- **Visual reference:** `source/RenewCMS Screens Auth.dc.html`, group "Accept invite" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
Opened from the invitation email. The link carries only the code, so the invited email is looked up on load and shown read-only. Username and password follow the Register rules, including PasswordStrengthHint, with no confirm field. On success the person is logged in and sent to /home with a toast. The account is already verified, because the invite went to their email, so it skips the pending and verify screens.
Neither endpoint exists yet:
- `GET /v1/auth/invite?c=CODE` returns `{ email }`, or 404 or 410.
- `POST /v1/auth/invite/accept` takes `{ code, username, password }`. It returns 200 with the session cookie, 409 for a taken username, or 404 or 410 as above.
Registration stays closed to everyone else: [register.md](register.md) "Registration closed" still applies to `/register`. The board does not draw the case of a logged-in person opening the link; it is not specified.
## States
### Checking the link
**Trigger:** On load, while the invite is looked up.
- Full-card spinner: "Checking your invite…"
### Default
**Trigger:** The code is valid and unused.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; counter "0 / 20"; help "Letters and numbers, 3 to 20 characters. You'll use it to log in."
- Field `Password`: password with show/hide; checklist "At least 8 characters" (unmet)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Validation errors
**Trigger:** Checked on blur and on submit, using the same rules as Register. Nothing is sent.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "ma"; counter "2 / 20" in error; **error "Use 3 to 20 characters."**
- Field `Password`: value "lime"; password with show/hide; checklist "At least 8 characters" (err)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Filled, valid
**Trigger:** Every rule is met and the checklist item turns green.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "lea"; counter "3 / 20"; help "Letters and numbers, 3 to 20 characters. You'll use it to log in."
- Field `Password`: value "limewash2026"; password with show/hide; password shown; checklist "At least 8 characters" (met)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Submitting
**Trigger:** Fields and button are disabled.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "lea"; counter "3 / 20"; help "Letters and numbers, 3 to 20 characters. You'll use it to log in."
- Field `Password`: value "limewash2026"; password with show/hide; checklist "At least 8 characters" (met)
- Submit button: "Creating account…", loading
- Footer: Already have an account? [Log in]
### Username taken (409)
**Trigger:** Another user has that username. The value is kept and the field gets focus.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "marta"; counter "5 / 20"; focused; **error "That username is taken. Try another."**
- Field `Password`: value "limewash2026"; password with show/hide; checklist "At least 8 characters" (met)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Invalid or used link (404)
**Trigger:** The code is wrong, was already accepted, or is missing from the URL. No form is shown.
- ResultPanel (error, link-2-off): **This invite link doesn't work**; text "It may be incomplete, or it may already have been used. If you already set up your account, log in instead."; note "Open the link from your email again, or copy the full address into your browser."; actions "Go to log in" (primary)
### Expired link (410)
**Trigger:** The invite is older than 3 days.
- ResultPanel (error, clock): **This invite has expired**; text "Invites work once, for 3 days. Ask the person who invited you to send a new one."; actions "Go to log in" (secondary)
### Server error
**Trigger:** A 500 or no response. The values are kept.
- Alert (error, circle-x): **Couldn't create the account** "Something went wrong on the server. Try again in a moment."
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "lea"; counter "3 / 20"; help "Letters and numbers, 3 to 20 characters. You'll use it to log in."
- Field `Password`: value "limewash2026"; password with show/hide; checklist "At least 8 characters" (met)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Success
**Trigger:** 200 sets the session cookie → /home after 800 ms, with a toast. No verification step.
- ResultPanel (success, circle-check): **Your account is ready**; text "Taking you to your dashboard…"
- Toast (circle-check): **Welcome to RenewCMS** "You're logged in as lea."
+39 -2
View File
@@ -83,13 +83,50 @@ On mobile, Save and Publish sit in a sticky bottom bar and the details panel ope
- Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis
### Upload: crop and resize
**Trigger:** A JPEG, PNG or WEBP passed the checks, and nothing is sent yet. The crop starts as the whole image and the width defaults to 1600 px. SVGs skip this step.
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Crop and resize** "north-wall.jpg · 3.9 MB"
- crop: ratio "Original", width "1600 px"
- cancel "Choose another file"
- confirm "Upload image"
- Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis
### Upload: crop to a ratio
**Trigger:** 16:9 chosen. The frame keeps the ratio while it's dragged or resized. Arrow keys move it; Shift and arrow keys resize it.
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Crop and resize** "north-wall.jpg · 3.9 MB"
- crop: ratio "16:9", width "1600 px"
- cancel "Choose another file"
- confirm "Upload image"
- Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis
### Upload: crop narrower than the width
**Trigger:** The crop is smaller than the chosen width, so it keeps its own size.
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Crop and resize** "north-wall.jpg · 3.9 MB"
- crop: ratio "1:1", width "1600 px"
- note: "The crop is 640 px wide, so it's uploaded at that size. Enlarging it would make it blurry."
- cancel "Choose another file"
- confirm "Upload image"
- Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis
### Upload: in progress
**Trigger:** A valid file is uploading. Closing the dialog cancels the upload.
**Trigger:** Upload image was pressed. The cropped, resized file is uploading. Closing the dialog cancels the upload.
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Add an image**
- upload state: state "uploading"
- upload state: state "uploading" ("Uploading 180 of 420 KB")
- cancel "Cancel upload"
- Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis
+1 -1
View File
@@ -4,7 +4,7 @@
- **API:** GET /v1/article/
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Home" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
The counts come from the list, so there's no separate endpoint. The five most recently updated articles link to the editor.
The greeting reads "Good morning, {name}", where the name is the display name when the user has saved one and the username otherwise. The counts come from the list, so there's no separate endpoint. The five most recently updated articles link to the editor.
## States
+179
View File
@@ -0,0 +1,179 @@
# Profile
- **Route:** `/profile`
- **API:** GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Profile" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters.
Once saved it replaces the username everywhere a person is named:
- the sidebar chip and the account menu (name, and the avatar initials)
- the Home greeting ("Good morning, Marta Alves")
- the Display name column of the Users list
- the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS"
Saving it empty goes back to the username. Logging in still uses the username.
The reset link uses the same flow as "Forgot password" and ends on the auth board's "Choose a new password" screen ([reset-password.md](reset-password.md)).
## The page
Three cards under the title "Profile" and the subtitle "Your account on this RenewCMS workspace.", 720 px wide at most.
| Card | Content |
|---|---|
| Display name | Title "Display name". Text "Shown instead of your username across the back-office and in the emails RenewCMS sends. Leave it empty to use your username." One input, label "Display name (optional)", placeholder "e.g. Marta Alves", with a live counter "n / 60" in mono on the right of the help row. A footer strip holds a status line on the left and the Save button on the right. |
| Account | Title "Account". Text "Set when your account was created. You log in with your username, even after adding a display name." Two disabled inputs with a lock icon: Username and Email (two columns on desktop, one on mobile). |
| Password | Title "Password". Text "To change it, we'll email a reset link to marta@renew.example. The link works once, within 1 hour." A disabled input showing "••••••••••••" beside the button "Send reset link" (mail icon). A note appears under them once a request has been made. |
**Footer status line** (12 px): "Unsaved changes" in the warning color while dirty and not saving. Otherwise "You appear as “Marta Alves”." when a display name is saved, or "You appear as “marta”, your username." when it isn't.
**Save button:** full opacity when the value changed and is valid, or while saving. 40 % opacity and inert otherwise. Enter in the field saves.
**Counting:** characters are counted as Unicode characters, not bytes or UTF-16 units. The counter turns red over 60.
**Leaving the page** with unsaved changes asks for confirmation.
**Mobile:** cards use 16 px padding, inputs are 44 px, the two account inputs stack, and the password input and its button stack.
## The account menu
Opened from the account chip at the bottom of the sidebar (chevrons-up-down icon; `aria-haspopup="menu"`, `aria-expanded`). The chip takes the sand fill with ink text while the menu is open, and while `/profile` is the current page.
Desktop: a 224 px popover above the chip, aligned to its left. Mobile: the account row in the navigation drawer opens it as a bottom sheet with a grab handle. Escape or a click outside closes both.
| Part | Content |
|---|---|
| Header | The name in semibold (display name, or the username), and the email in muted 12 px (14 px on mobile, with a 36 px initials avatar beside them) |
| Item | Profile (circle-user icon), highlighted while on `/profile` |
| Separator | |
| Items | System, Light, Dark: a radio-style group, the current choice carries a check icon at the right edge; choosing one applies the theme at once and keeps the menu open |
| Separator | |
| Item | Log out (log-out icon) |
Avatar initials come from the first letters of the first two words of the display name, uppercased ("Marta Alves" gives MA). Without a display name they come from the username.
The board's menu now carries System, Light and Dark, matching the shipped UserMenu. The theme choice stays in the account menu; the Profile page does not repeat it. Items are 32 px on desktop and 48 px in the mobile sheet.
## States
### Account menu
**Trigger:** The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.
- Breadcrumbs: Home (mobile title "Home")
- Page behind the menu: Home, default
- Menu open, as described above, with the System, Light and Dark group between Profile and Log out. The board shows Light checked
### Loading
**Trigger:** Opened directly by URL before /auth/me has returned. From the menu, the cached user renders straight away.
- Breadcrumbs: Profile (mobile title "Profile")
- Three skeleton cards (one input, two inputs, one input)
### Default, no display name
**Trigger:** The usual first visit. The username is used everywhere.
- Breadcrumbs: Profile (mobile title "Profile")
- Display name: empty, placeholder "e.g. Marta Alves", counter "0 / 60"
- Footer: "You appear as “marta”, your username."
- Save: 40 % opacity
### Editing
**Trigger:** Typing in the field. Save turns on, and leaving the page asks for confirmation.
- Breadcrumbs: Profile (mobile title "Profile")
- Display name: "Marta Alves"; focused; counter "11 / 60"
- Footer: "Unsaved changes" (warning)
- Save: enabled
### Too long
**Trigger:** Over 60 characters. Checked as you type, and Save stays off.
- Breadcrumbs: Profile (mobile title "Profile")
- Display name: "Marta Alves, Head of Renovations, Brussels and Wallonia office"; focused; counter red
- **Error "Use 60 characters or fewer."**
- Footer: "Unsaved changes" (warning)
- Save: 40 % opacity
### Saving
**Trigger:** Save, or Enter in the field. The field is disabled.
- Breadcrumbs: Profile (mobile title "Profile")
- Display name: "Marta Alves", disabled, dimmed
- Save: "Saving…" with a loader
### Saved
**Trigger:** 200: the sidebar and account menu switch to the display name at once, and a toast confirms.
- Breadcrumbs: Profile (mobile title "Profile")
- Sidebar chip: "Marta Alves", initials MA
- Display name: "Marta Alves"; counter "11 / 60"
- Footer: "You appear as “Marta Alves”."
- Toast (success, circle-check): **Display name saved** "You now appear as Marta Alves across RenewCMS and in emails."
### Save failed
**Trigger:** 500 or network failure. The typed value is kept.
- Breadcrumbs: Profile (mobile title "Profile")
- Alert (error) in the Display name card: "Couldn't save your display name. Your text is still here. Try again in a moment."
- Display name: "Marta Alves"
- Footer: "Unsaved changes" (warning)
- Save: enabled
### Reset: sending
**Trigger:** "Send reset link". No confirmation, since it only sends an email.
- Breadcrumbs: Profile (mobile title "Profile")
- Button: "Sending…" with a loader
- Sidebar chip shows the display name "Marta Alves"
### Reset: sent
**Trigger:** 200. The message stays until the page is left. "Send again" sends a new link and the old one stops working.
- Breadcrumbs: Profile (mobile title "Profile")
- Button: "Send again" (mail)
- Note (success, mail-check): **Reset link sent** "Check marta@renew.example. The link works once, within 1 hour."
### Reset: too many requests (429)
**Trigger:** Rate limited. The button is disabled for 5 minutes.
- Breadcrumbs: Profile (mobile title "Profile")
- Button: "Send reset link", 40 % opacity, disabled
- Note (warning, clock-alert): **Too many requests** "You've asked for several links recently. Wait a few minutes, then try again."
### Reset: failed
**Trigger:** 500 or network failure. The button can be pressed again.
- Breadcrumbs: Profile (mobile title "Profile")
- Button: "Send reset link"
- Note (error, circle-x): **Couldn't send the link** "Check your connection and try again."
### Display names in the Users list
**Trigger:** The Display name column of the Users list shows the name when one is set and a dash when not. Your own row follows your saved name. This state needs the Users page ([users.md](users.md)).
- Breadcrumbs: Users (mobile title "Users")
- Signed-in user's display name: "Marta Alves" (sidebar chip shows it too)
- Row `marta@renew.example` (you): display name "Marta Alves", role owner, Accepted
- Row `ines.duarte@renew.example`: display name "Inès Duarte", role admin, Accepted
- Row `jonas@renew.example`: display name "—" (muted), role admin, Accepted
## Notes for implementation
- `PATCH /v1/user/me` is marked pending by the design: it does not exist yet. `GET /v1/auth/me` has to start returning the display name.
- The Password card sends the reset email to the account's own address through the existing `POST /v1/auth/password-reset`. The link ends on the reset confirm screen, and a successful reset invalidates the current session like any other reset.
- "Disabled for 5 minutes" is the design's number. The real window comes from the `Retry-After` header, as on the login and reset screens.
- Resolved: the theme choice (System, Light, Dark) stays in the account menu, as the board now draws it. The board still draws Profile highlighted on Home; the app highlights it only on `/profile`.
+35
View File
@@ -0,0 +1,35 @@
# Settings
- **Route:** `/settings`
- **API:** GET /v1/settings (not drawn, see the notes)
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it, owner and admins alike. For now it holds a single section, Version. Nothing on it can be edited.
## The page
Title "Settings" and the subtitle "Workspace information.", 720 px wide at most. Page padding 32 px on desktop and `20px 16px 88px` on mobile, 20 px between the header and the card.
One card (`--ui-bg`, 1 px `--ui-border`, 20 px padding on desktop and 16 px on mobile), a single row with the label on the left and the value on the right, 16 px apart:
| Part | Content |
|---|---|
| Label | "Version", 15 px semibold, `--ui-text-highlighted` |
| Value | The running build's version in IBM Plex Mono 14 px, `--ui-text-toned`. The board shows `v2.2.0-beta`. Shown exactly as the server reports it, so the SPA adds no `v` prefix. |
## States
### Default
**Trigger:** Opened from the sidebar.
- Breadcrumbs: Settings (mobile title "Settings")
- Section: Version, `v2.2.0-beta`
The board draws no loading or error state. Decide them in the spec (see the notes).
## Notes for implementation
- The board's API line says "none (static)", but the version lives in the Go binary (`main.version`, set with `-ldflags -X`, `dev` when unset), so the SPA has to ask for it. The recommendation is `GET /v1/settings` returning `{ "version": "..." }` inside the verified group, so later settings have a home. It is read once at startup and never from the environment at request time.
- Not drawn: loading (the recommendation is a skeleton for the value only, after 150 ms, like the other pages), and a failed request (an inline error in the card with "Try again", using the global copy "Couldn't reach RenewCMS. Check your connection and try again.").
- Keep the page free of actions, toggles and links until a later slice adds a real setting.
+232
View File
@@ -0,0 +1,232 @@
# Users
- **Route:** `/users`
- **API:** GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id (pending) · POST /v1/user/invite/:id/renew (pending)
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Users" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
One shared workspace: every user sees the same articles and this same list. The list shows email, display name, role, invite status and created date. A Pending invite can be cancelled and an Expired one renewed; accepted accounts have no row actions, so nobody can be removed or promoted from here. Only the owner can invite, cancel and renew (see "Roles").
An invite is **Pending** until its link is used, **Expired** after 3 days, and **Accepted** once the account is created. The list is sorted by created date, newest first.
## Roles
There are two roles. They are shown as a badge and are not editable.
| Role | Who | Can |
|---|---|---|
| owner | The account that registered first on the workspace. There is exactly one. | Everything an admin can, plus invite users, cancel invites and renew invites. |
| admin | Everyone who joined through an invite. Every invite creates an admin. | Read and write articles, see the Users list, edit their own profile, see Settings. |
The owner is the only difference for now. The role cannot be changed, transferred or removed from the UI.
**Not drawn by the board** (decide in the spec, cover by Vitest and Go tests only, like the 429 on invite):
- What a non-owner sees: the recommendation is to hide "Invite user" (desktop and mobile), hide the row actions, and hide the "Invite someone…" hint on the "Only you" state.
- The API answer when a non-owner calls an owner-only endpoint: the recommendation is 403 with a plain-text body, and no state change.
- The message if the owner's session sees a 403 anyway (role changed under it): the global 403 handling applies.
## The list
| Column | Content |
|---|---|
| Email | The account's or invite's email address, medium weight, highlighted. The current user's row carries a muted mono "you" tag after it. |
| Display name | The display name when set, highlighted; a muted dash `—` when not. An invite has none, so it shows the dash. Your own row follows your saved name. |
| Role | A mono 11 px badge, 20 px high: `owner` (filled, `--ui-primary` with `--ui-bg` text) or `admin` (transparent, toned text, `--ui-border-accented` border). An invite shows the role it will create, `admin`. |
| Invite status | A badge: Accepted (circle-check, success), Pending (mail, warning), Expired (clock-alert, outline, muted). Shown by icon and word as well as color. |
| Created | The date as `27 Sep 2026`, or "Today" for the current day. For an invite it is the day the invite was sent (or last renewed), for a user the day the account was created. |
| (actions) | Right-aligned, no header text. Pending row: "Cancel invite". Expired row: "Renew invite". Accepted row: empty. |
The username is no longer shown in this list.
Desktop is a table: 36 px header, 48 px rows, columns `minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px` with a 12 px gap. Below md it becomes a card list (68 px minimum row height): the email line (with "you"), the display name below it when there is one, then the role badge, the status badge and "Created {date}" on one line, then the row action, if any, as a 44 px button with 14 px side padding.
The page header is a title "Users" with the subtitle "Everyone who can sign in and work on your articles." and a primary "Invite user" button (user-plus icon) on its right. On mobile the button becomes a full-width 48 px button pinned to the bottom of the screen.
The owner is always listed, so the list is never empty.
### Row actions
| Action | Shown on | Icon | Look |
|---|---|---|---|
| Cancel invite | Pending | user-x | Outline button, text in `--ui-error` |
| Renew invite | Expired | refresh-cw | Outline button, text `--ui-text-highlighted` |
Desktop buttons are 28 px high, 12 px medium text, a 13 px icon, 9 px side padding, `--ui-border-accented` border, `--ui-bg` fill. Mobile buttons are 44 px high and 14 px side padding with a 14 px icon.
- **Cancel invite** asks first with a danger confirmation dialog, since it cannot be undone from here (the address can be invited again).
- **Renew invite** asks nothing, since it only sends an email. While the request runs, that row's button reads "Renewing…" with a loader-circle icon at 50 % opacity and is disabled. Only that row is busy.
## States
### Default
**Trigger:** The list loaded, newest first.
- Breadcrumbs: Users (mobile title "Users")
- Rows:
- `sam.oliveira@renew.example`, no display name, admin, Pending, 27 Sep 2026, "Cancel invite"
- `p.huber@gmail.com`, display name "Paul Huber", admin, Expired, 3 Aug 2026, "Renew invite"
- `ines.duarte@renew.example`, "Inès Duarte", admin, Accepted, 18 Jun 2026
- `jonas@renew.example`, no display name, admin, Accepted, 2 Apr 2026
- `marta@renew.example` (you), no display name, owner, Accepted, 12 Mar 2026
The board gives the Expired invite a display name. A real invite has none, so the SPA renders whatever `display_name` the item carries and the dash when it is empty.
### Loading
**Trigger:** The first load, or a retry. Skeletons appear after 150 ms.
- Breadcrumbs: Users (mobile title "Users")
- Five skeleton rows, one bar per column, plus a role-badge and a status-badge placeholder
### Only you
**Trigger:** Nobody has been invited yet. The owner is always listed.
- Breadcrumbs: Users (mobile title "Users")
- One row: `marta@renew.example` (you), owner, Accepted
- Hint under the list: "Invite someone so they can sign in with their own account instead of sharing yours."
### Error
**Trigger:** A 500 or network failure on the list request.
- Breadcrumbs: Users (mobile title "Users")
- Alert (error): **Couldn't load users** "Check your connection and try again."
- Action "Try again" (rotate-cw)
- No table or cards
### Invite: default
**Trigger:** "Invite user" in the page header, or the bottom button on mobile.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user**
- text "We'll email them a link to choose a username and password. The link expires after 3 days."
- field `Email`: placeholder "name@example.com"; focused
- close button
- cancel "Cancel"
- confirm "Send invite"
### Invite: validation
**Trigger:** On submit or blur. Nothing is sent.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user** (same text)
- field `Email`: value "sam.oliveira@renew"; **error "Enter a full email address, like name@example.com."**
- cancel "Cancel"
- confirm "Send invite"
### Invite: sending
**Trigger:** Request in flight. The field is disabled and the dialog can't be dismissed.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user** (same text)
- field `Email`: value "lea.martin@renew.example"; disabled
- cancel "Cancel"
- confirm "Sending…", loading, not dismissible
### Invite: already a user (409)
**Trigger:** The email belongs to an existing user. For a live pending invite the message reads "There's already a pending invite for this address." An expired invite can be sent again.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user** (same text)
- field `Email`: value "jonas@renew.example"; **error "This address already has an account."**
- cancel "Cancel"
- confirm "Send invite"
### Invite: failed
**Trigger:** 500, network failure, or the email couldn't be sent. The address stays in the field.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user** (same text)
- field `Email`: value "lea.martin@renew.example"
- Alert: "Couldn't send the invite. Try again in a moment."
- cancel "Cancel"
- confirm "Send invite"
### Invite sent
**Trigger:** 201: the dialog closes, the new invite appears at the top as Pending (highlighted row), and a toast confirms.
- Breadcrumbs: Users (mobile title "Users")
- New first row: `lea.martin@renew.example`, no display name, admin, Pending, created "Today", row background `--ui-bg-elevated`, with "Cancel invite"
- Toast (success, circle-check): **Invite sent** "lea.martin@renew.example has 3 days to accept."
The "Today" label makes this state clock-sensitive, so `task visual:check` skips it.
### Cancel invite: confirm
**Trigger:** "Cancel invite" on a Pending row.
- Breadcrumbs: Users (mobile title "Users")
- Modal (danger): **Cancel this invite?**
- text "The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later."
- cancel "Keep invite"
- confirm "Cancel invite"
### Cancel invite: sending
**Trigger:** Request in flight. Both buttons are disabled and the dialog can't be dismissed.
- Breadcrumbs: Users (mobile title "Users")
- Modal (danger): **Cancel this invite?** (same text)
- cancel "Keep invite", disabled
- confirm "Cancelling…", loading
### Cancel invite: failed
**Trigger:** 500 or network failure. The dialog stays open.
- Breadcrumbs: Users (mobile title "Users")
- Modal (danger): **Cancel this invite?** (same text)
- notice "Couldn't cancel the invite. Try again in a moment."
- cancel "Keep invite"
- confirm "Cancel invite"
### Cancel invite: done
**Trigger:** 204: the row disappears and a toast confirms.
- Breadcrumbs: Users (mobile title "Users")
- The Pending row `sam.oliveira@renew.example` is gone; the other four remain
- Toast (success, circle-check): **Invite cancelled** "sam.oliveira@renew.example can no longer use the link."
### Renew invite: sending
**Trigger:** "Renew invite" on an Expired row. No confirmation, since it only sends an email. The button shows progress and is disabled.
- Breadcrumbs: Users (mobile title "Users")
- The Expired row's button reads "Renewing…" with a loader-circle icon, 50 % opacity, disabled
### Renew invite: done
**Trigger:** 200: the row becomes Pending with today's date, moves to the top, and the old link stops working.
- Breadcrumbs: Users (mobile title "Users")
- First row: `p.huber@gmail.com` Pending, created "Today", row background `--ui-bg-elevated`, now with "Cancel invite"
- Toast (success, circle-check): **Invite renewed** "p.huber@gmail.com has 3 days to accept the new link."
The "Today" label makes this state clock-sensitive, so `task visual:check` skips it.
### Renew invite: failed
**Trigger:** 500 or network failure. The row stays Expired and the button can be pressed again.
- Breadcrumbs: Users (mobile title "Users")
- Toast (error, circle-x): **Couldn't renew the invite** "Try again in a moment."
## Notes for implementation
- Accepted users are now listed by email, display name and role. This reverses the earlier rule that a user is never listed with an email.
- How display names look in this list is the state "Display names in the Users list" of [profile.md](profile.md). The board draws it in the Profile group, and `task visual:check` finds states by group.
- The board's API line marks both new endpoints "(pending)", meaning "not built yet". Cancel applies to a Pending invite. Renew is drawn on an Expired one; the recommendation is that the API also accepts a Pending one (it resets the 3 days and replaces the link) and refuses an Accepted one with 409. The SPA only offers Renew on Expired rows.
- Renewing replaces the code and expiry, resets the created date to now, and sends the invitation email again. The old link stops working. The email is specified in [emails.md](../emails.md).
- A 404 on cancel or renew (the invite was already used or cancelled elsewhere) is not drawn. Decide it in the spec; the recommendation is to drop the row and toast the outcome.
- 429 on the invite request is not drawn. Decide it in the spec before coding.
- The email the invite sends is specified in [emails.md](../emails.md). The screen the link opens is in [accept-invite.md](accept-invite.md).
- The role rules and what is not drawn are in "Roles" above.
+154 -8
View File
@@ -16,8 +16,9 @@
</sc-for>
<div style="flex:1"></div>
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
<sc-if value="{{ notBoot }}"><div data-act="logout" title="Log out" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">MA</span><span style="flex:1;color:var(--ui-text-highlighted)">marta</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></div></sc-if>
<sc-if value="{{ notBoot }}"><div data-act="usermenu" role="button" aria-haspopup="menu" aria-expanded="{{ menuOpen }}" title="Account" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;background:{{ chipBg }};color:{{ chipFg }}"><span style="width:26px;height:26px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500">{{ who }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></div></sc-if>
</div>
<sc-if value="{{ deskMenu }}"><div role="menu" aria-label="Account" style="position:absolute;left:12px;bottom:56px;z-index:40;width:224px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div style="padding:8px 8px 10px;display:flex;flex-direction:column;gap:2px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="font-weight:600;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ who }}</span><span style="font-size:12px;color:var(--ui-text-muted)">marta@renew.example</span></div><div data-act="nav-profile" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:32px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;font-size:14px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></sc-if>
</sc-if>
<div style="flex:1;min-width:0;min-height:0;display:flex;flex-direction:column">
<sc-if value="{{ desk }}" hint-placeholder-val="{{ true }}">
@@ -41,7 +42,7 @@
<sc-if value="{{ isHome }}">
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:{{ gap }};max-width:1040px">
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Good morning, marta</span><span style="color:var(--ui-text-muted);font-size:14px">{{ s.home.sub }}</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div>
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Good morning, {{ who }}</span><span style="color:var(--ui-text-muted);font-size:14px">{{ s.home.sub }}</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div>
<sc-if value="{{ s.home.error }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load your articles</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
<sc-if value="{{ s.home.stats }}">
<div style="display:grid;grid-template-columns:{{ cols3 }};gap:12px">
@@ -128,7 +129,7 @@
<span data-act="preview" style="display:flex;align-items:center;gap:8px;white-space:nowrap;flex-shrink:0;color:var(--ui-text-toned)"><span style="width:32px;height:18px;padding:2px;display:flex;justify-content:{{ pvJust }};background:{{ pvBg }}"><span style="width:14px;height:14px;background:var(--ui-bg)"></span></span>Preview</span>
<span data-act="save" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500;opacity:{{ saveOp }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat"></span>Save</span>
<span data-act="publish" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;font-weight:500;background:{{ pub.bg }};color:{{ pub.fg }};border:1px solid {{ pub.bd }};opacity:{{ pub.op }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ pub.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ pub.icon }}.svg') center / contain no-repeat"></span>{{ pub.t }}</span>
<span data-act="overflow" style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center;color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat"></span></span>
<span data-act="overflow" role="button" aria-label="Delete article" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;font-weight:500;border:1px solid var(--ui-error);color:var(--ui-error);cursor:pointer"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat"></span>Delete</span>
</sc-if>
</sc-if>
</div>
@@ -195,6 +196,73 @@
</div>
</sc-if>
<sc-if value="{{ isUsers }}">
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:16px;flex:1;min-height:0">
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Users</span><span style="color:var(--ui-text-muted)">Everyone who can sign in and work on your articles.</span></div><sc-if value="{{ desk }}"><span data-act="invite" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat"></span>Invite user</span></sc-if></div>
<sc-if value="{{ usError }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load users</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:{{ btnH }};padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
<sc-if value="{{ usTable }}">
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
<div style="display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px;gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Email</span><span>Display name</span><span>Role</span><span>Invite status</span><span style="display:flex;align-items:center;gap:4px;color:var(--ui-text-highlighted)">Created<span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat"></span></span><span></span></div>
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
<div style="display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px;gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:{{ r.bg }}">
<sc-if value="{{ r.skel }}"><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span><span style="height:12px;width:50%;background:var(--ui-bg-accented)"></span><span style="width:52px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:76px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></sc-if>
<sc-if value="{{ r.email }}"><span style="display:flex;align-items:center;gap:8px;min-width:0"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;color:{{ r.fg }}">{{ r.email }}</span><sc-if value="{{ r.you }}"><span style="flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">you</span></sc-if></span><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:{{ r.dfg }}">{{ r.dn }}</span><span><span style="height:20px;padding:0 7px;display:inline-flex;align-items:center;background:{{ r.rl.bg }};color:{{ r.rl.fg }};border:1px solid {{ r.rl.bd }};font:500 11px 'IBM Plex Mono',monospace">{{ r.rl.t }}</span></span><span><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;background:{{ r.b.bg }};color:{{ r.b.fg }};border:1px solid {{ r.b.bd }};font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat"></span>{{ r.b.t }}</span></span><span style="color:var(--ui-text-muted)">{{ r.c }}</span><span style="display:flex;justify-content:flex-end"><sc-if value="{{ r.act }}"><span data-act="{{ r.act.key }}" style="height:28px;padding:0 9px;white-space:nowrap;flex-shrink:0;display:inline-flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ r.act.fg }};font-weight:500;font-size:12px;opacity:{{ r.act.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:13px;height:13px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat"></span>{{ r.act.t }}</span></sc-if></span></sc-if>
</div>
</sc-for>
</div>
</sc-if>
<sc-if value="{{ usCards }}">
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);margin:0 -16px;border-left:0;border-right:0">
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
<div style="display:flex;flex-direction:column;justify-content:center;gap:6px;padding:12px 16px;border-bottom:1px solid var(--ui-border);min-height:68px;background:{{ r.bg }}">
<sc-if value="{{ r.skel }}"><span style="width:55%;height:14px;background:var(--ui-bg-accented)"></span><span style="width:40%;height:12px;background:var(--ui-bg-accented)"></span></sc-if>
<sc-if value="{{ r.email }}"><span style="display:flex;align-items:center;gap:8px;min-width:0"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:15px;line-height:21px;font-weight:500;color:{{ r.fg }}">{{ r.email }}</span><sc-if value="{{ r.you }}"><span style="flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">you</span></sc-if></span><sc-if value="{{ r.display2 }}"><span style="color:var(--ui-text-toned)">{{ r.dn }}</span></sc-if><div style="display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)"><span style="height:20px;padding:0 7px;display:inline-flex;align-items:center;background:{{ r.rl.bg }};color:{{ r.rl.fg }};border:1px solid {{ r.rl.bd }};font:500 11px 'IBM Plex Mono',monospace">{{ r.rl.t }}</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;background:{{ r.b.bg }};color:{{ r.b.fg }};border:1px solid {{ r.b.bd }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat"></span>{{ r.b.t }}</span><span>Created {{ r.c }}</span></div><sc-if value="{{ r.act }}"><div style="display:flex;padding-top:4px"><span data-act="{{ r.act.key }}" style="height:44px;padding:0 14px;white-space:nowrap;flex-shrink:0;display:inline-flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ r.act.fg }};font-weight:500;font-size:13px;opacity:{{ r.act.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat"></span>{{ r.act.t }}</span></div></sc-if></sc-if>
</div>
</sc-for>
</div>
</sc-if>
<sc-if value="{{ usOnly }}"><span style="color:var(--ui-text-muted);text-wrap:pretty">Invite someone so they can sign in with their own account instead of sharing yours.</span></sc-if>
</div>
<sc-if value="{{ mob }}"><sc-if value="{{ listFab }}"><div data-act="invite" style="position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat"></span>Invite user</div></sc-if></sc-if>
</sc-if>
<sc-if value="{{ isSettings }}">
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Settings</span><span style="color:var(--ui-text-muted)">Workspace information.</span></div>
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">v2.2.0-beta</span></div>
</div>
</sc-if>
<sc-if value="{{ isProfile }}">
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Profile</span><span style="color:var(--ui-text-muted)">Your account on this RenewCMS workspace.</span></div>
<sc-if value="{{ pfLoading }}"><div aria-busy="true" style="display:flex;flex-direction:column;gap:16px"><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:12px"><span style="width:120px;height:14px;background:var(--ui-bg-accented)"></span><span style="height:40px;background:var(--ui-bg-accented)"></span></div><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:12px"><span style="width:90px;height:14px;background:var(--ui-bg-accented)"></span><span style="height:40px;background:var(--ui-bg-accented)"></span><span style="height:40px;background:var(--ui-bg-accented)"></span></div><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:12px"><span style="width:100px;height:14px;background:var(--ui-bg-accented)"></span><span style="height:40px;background:var(--ui-bg-accented)"></span></div></div></sc-if>
<sc-if value="{{ pfReady }}">
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
<div style="padding:{{ cardPad }};display:flex;flex-direction:column;gap:14px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Display name</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Shown instead of your username across the back-office and in the emails RenewCMS sends. Leave it empty to use your username.</span></div>
<sc-if value="{{ pf.notice }}"><div role="alert" style="display:flex;gap:8px;padding:10px 12px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><span style="color:var(--ui-text-toned)">{{ pf.notice }}</span></div></sc-if>
<div style="display:flex;flex-direction:column;gap:6px">
<label style="font-weight:500;color:var(--ui-text-highlighted)">Display name <span style="font-weight:400;color:var(--ui-text-muted)">(optional)</span></label>
<div style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;border:1px solid {{ dn.bd }};box-shadow:{{ dn.sh }};background:{{ dn.bg }};color:{{ dn.fg }};font-size:{{ inF }};overflow:hidden;white-space:nowrap"><span style="overflow:hidden;text-overflow:ellipsis">{{ dn.shown }}</span><sc-if value="{{ dn.caret }}"><span style="flex-shrink:0;display:inline-block;width:1px;height:18px;background:var(--ui-text-highlighted);margin-left:1px"></span></sc-if></div>
<div style="display:flex;gap:12px;align-items:flex-start"><span style="flex:1;display:flex;gap:6px;align-items:center;color:var(--ui-error);font-size:12px"><sc-if value="{{ dn.err }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-alert.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-alert.svg') center / contain no-repeat"></span>{{ dn.err }}</sc-if></span><span style="font:400 12px 'IBM Plex Mono',monospace;color:{{ dn.countFg }}">{{ dn.count }}</span></div>
</div>
</div>
<div style="padding:12px {{ cardPadX }};border-top:1px solid var(--ui-border);background:var(--ui-bg-muted);display:flex;align-items:center;gap:12px"><span style="flex:1;min-width:0;color:{{ dn.footFg }};font-size:12px;line-height:18px">{{ dn.foot }}</span><span data-act="pf-save" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;gap:6px;flex-shrink:0;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;opacity:{{ dnSave.op }}"><sc-if value="{{ dnSave.loading }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat"></span></sc-if>{{ dnSave.t }}</span></div>
</div>
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:14px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Account</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Set when your account was created. You log in with your username, even after adding a display name.</span></div>
<div style="display:grid;grid-template-columns:{{ pfCols }};gap:14px"><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Username</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">marta</span><span style="display:flex;color:var(--ui-text-dimmed)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Email</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">marta@renew.example</span><span style="display:flex;color:var(--ui-text-dimmed)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div></div>
</div>
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:14px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Password</span><span style="color:var(--ui-text-muted);text-wrap:pretty">To change it, we'll email a reset link to marta@renew.example. The link works once, within 1 hour.</span></div>
<div style="display:flex;flex-direction:{{ pwDir }};align-items:{{ pwAlign }};gap:12px"><div style="flex:1;min-width:0"><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Password</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;letter-spacing:0.12em">••••••••••••</span><span style="display:flex;color:var(--ui-text-dimmed)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div></div><span data-act="pf-reset" style="height:{{ inH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;flex-shrink:0;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;white-space:nowrap;opacity:{{ rsBtn.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ rsBtn.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ rsBtn.icon }}.svg') center / contain no-repeat"></span>{{ rsBtn.t }}</span></div>
<sc-if value="{{ rsNote }}"><div role="status" style="display:flex;gap:10px;padding:12px 14px;background:{{ rsNote.bg }}"><span style="display:flex;padding-top:2px;color:{{ rsNote.fg }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ rsNote.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ rsNote.icon }}.svg') center / contain no-repeat"></span></span><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;color:{{ rsNote.fg }}">{{ rsNote.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ rsNote.text }}</span></div></div></sc-if>
</div>
</sc-if>
</div>
</sc-if>
<sc-if value="{{ isError }}">
<div style="padding:{{ errPad }};display:flex;flex-direction:column;gap:14px;max-width:560px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ s.err.code }}</span><span style="font:600 24px/32px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.err.title }}</span><span style="color:var(--ui-text-toned);font-size:14px;line-height:22px;text-wrap:pretty">{{ s.err.text }}</span><div style="display:flex;gap:8px;flex-wrap:wrap"><span data-act="err-primary" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">{{ s.err.primary }}</span><sc-if value="{{ s.err.secondary }}"><span style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">{{ s.err.secondary }}</span></sc-if></div></div>
</sc-if>
@@ -202,6 +270,8 @@
</div>
</div>
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
<sc-if value="{{ s.modal }}">
<div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}">
<div role="dialog" aria-modal="true" style="width:{{ modalW }};background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column">
@@ -214,6 +284,41 @@
<sc-if value="{{ s.modal.upload }}">
<div data-act="upload-pick" style="height:180px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:16px;text-align:center;border:{{ up.bd }};background:{{ up.bg }};color:{{ up.fg }}"><span aria-hidden="true" style="display:inline-block;width:24px;height:24px;background-color:{{ up.ic }};-webkit-mask:url('https://api.iconify.design/lucide/{{ up.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ up.icon }}.svg') center / contain no-repeat"></span><span style="font-weight:500;color:var(--ui-text-highlighted)">{{ up.title }}</span><sc-if value="{{ up.progress }}"><div style="width:80%;height:4px;background:var(--ui-bg-accented)"><div style="width:{{ up.progress }};height:4px;background:var(--ui-primary)"></div></div></sc-if><span style="color:var(--ui-text-toned);font-size:12px;max-width:300px">{{ up.text }}</span></div>
</sc-if>
<sc-if value="{{ s.modal.crop }}">
<div style="display:flex;flex-direction:column;gap:16px">
<div style="height:{{ cr.stageH }};padding:16px;background:var(--ui-bg-elevated);display:flex;align-items:center;justify-content:center">
<div role="img" aria-label="north-wall.jpg, 4032 × 3024 px" style="position:relative;height:100%;max-width:100%;aspect-ratio:4/3;overflow:hidden;background:#d8d0c3">
<div style="position:absolute;left:0;right:0;bottom:0;height:32%;background:#8f8373"></div>
<div style="position:absolute;left:56%;top:14%;width:22%;height:42%;background:#f1ece3;border:6px solid #c4b9a8"></div>
<div tabindex="0" aria-label="Crop area. Arrow keys move it, Shift and arrow keys resize it." style="position:absolute;left:{{ cr.l }};top:{{ cr.t }};width:{{ cr.w }};height:{{ cr.h }};box-shadow:0 0 0 2000px rgb(10 10 10 / 0.55);outline:1px solid #ffffff;cursor:move">
<div style="position:absolute;left:33.333%;top:0;bottom:0;width:1px;background:rgb(255 255 255 / 0.45)"></div>
<div style="position:absolute;left:66.666%;top:0;bottom:0;width:1px;background:rgb(255 255 255 / 0.45)"></div>
<div style="position:absolute;top:33.333%;left:0;right:0;height:1px;background:rgb(255 255 255 / 0.45)"></div>
<div style="position:absolute;top:66.666%;left:0;right:0;height:1px;background:rgb(255 255 255 / 0.45)"></div>
<div style="position:absolute;left:-6px;top:-6px;width:12px;height:12px;background:#ffffff;border:1px solid #111111"></div>
<div style="position:absolute;right:-6px;top:-6px;width:12px;height:12px;background:#ffffff;border:1px solid #111111"></div>
<div style="position:absolute;left:-6px;bottom:-6px;width:12px;height:12px;background:#ffffff;border:1px solid #111111"></div>
<div style="position:absolute;right:-6px;bottom:-6px;width:12px;height:12px;background:#ffffff;border:1px solid #111111"></div>
<span style="position:absolute;left:8px;bottom:8px;padding:1px 6px;background:rgb(17 17 17 / 0.8);color:#ffffff;font:400 11px/18px 'IBM Plex Mono',monospace;white-space:nowrap">{{ cr.dims }}</span>
</div>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<div style="display:flex;align-items:center;gap:4px"><span style="flex:1;font-weight:500;color:var(--ui-text-highlighted)">Aspect ratio</span><span data-act="crop-rotate" style="height:{{ btnH }};padding:0 8px;display:flex;align-items:center;gap:6px;color:var(--ui-text-toned);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-ccw-square.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-ccw-square.svg') center / contain no-repeat"></span>Rotate</span><span data-act="crop-reset" style="height:{{ btnH }};padding:0 8px;display:flex;align-items:center;gap:6px;color:var(--ui-text-toned);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/undo-2.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/undo-2.svg') center / contain no-repeat"></span>Reset</span></div>
<div role="radiogroup" aria-label="Aspect ratio" style="display:flex;border:1px solid var(--ui-border-accented);width:{{ cr.groupW }}">
<sc-for list="{{ cr.ratios }}" as="p" hint-placeholder-count="5"><span role="radio" aria-checked="{{ p.on }}" data-act="{{ p.act }}" style="flex:{{ cr.pillFlex }};height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;font-weight:500;white-space:nowrap;background:{{ p.bg }};color:{{ p.fg }}">{{ p.t }}</span></sc-for>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<span style="font-weight:500;color:var(--ui-text-highlighted)">Width</span>
<div role="radiogroup" aria-label="Width" style="display:flex;border:1px solid var(--ui-border-accented);width:{{ cr.groupW }}">
<sc-for list="{{ cr.sizes }}" as="p" hint-placeholder-count="4"><span role="radio" aria-checked="{{ p.on }}" data-act="{{ p.act }}" style="flex:{{ cr.pillFlex }};height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;font-weight:500;white-space:nowrap;background:{{ p.bg }};color:{{ p.fg }}">{{ p.t }}</span></sc-for>
</div>
<span style="font:400 12px/18px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ cr.out }}</span>
</div>
<sc-if value="{{ cr.note }}"><div role="status" style="display:flex;gap:8px;padding:10px 12px;background:var(--rc-info-soft)"><span style="display:flex;padding-top:2px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ cr.note }}</span></div></sc-if>
</div>
</sc-if>
</div>
<div style="padding:20px 24px;display:flex;flex-direction:{{ mBtnDir }};justify-content:flex-end;gap:8px">
<sc-if value="{{ s.modal.cancel }}"><span data-act="modal-cancel" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:{{ mCancelFg }};font-weight:500">{{ s.modal.cancel }}</span></sc-if>
@@ -238,7 +343,7 @@ class Component extends DCLogic {
const s = this.props.s || {}
const m = !!this.props.mobile
const k = s.kind || 'home'
const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['integration', 'plug', 'Integration']]
const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
const L = s.list || {}
@@ -264,12 +369,48 @@ class Component extends DCLogic {
const mFields = (md.fields || []).map(f => { const has = f.value; return { ...f, shown: has || f.ph || '', fg: md.loading ? 'var(--ui-text-dimmed)' : has ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', bd: f.err ? 'var(--ui-error)' : f.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)', sh: f.err ? 'inset 0 0 0 1px var(--ui-error)' : f.focus ? 'inset 0 0 0 1px var(--ui-primary)' : 'none', bg: md.loading ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)', h: f.area ? (m ? '120px' : '96px') : (m ? '44px' : '40px'), p: f.area ? '8px 10px' : '0 10px', ai: f.area ? 'flex-start' : 'center', countFg: f.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)' } })
const U = md.upload || {}
const upMap = {
uploading: { icon: 'image-plus', ic: 'var(--ui-text-toned)', title: 'north-wall.jpg', text: 'Uploading 2.4 of 3.9 MB', progress: '62%', bd: '1px solid var(--ui-border)', bg: 'var(--ui-bg)' },
uploading: { icon: 'image-plus', ic: 'var(--ui-text-toned)', title: 'north-wall.jpg', text: 'Uploading 180 of 420 KB', progress: '43%', bd: '1px solid var(--ui-border)', bg: 'var(--ui-bg)' },
rejected: { icon: 'file-x', ic: 'var(--ui-error)', title: 'north-wall.tif is 14.2 MB', text: 'Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image.', bd: '1px solid var(--ui-error)', bg: 'var(--ui-bg)' },
idle: { icon: 'image-plus', ic: 'var(--ui-text-toned)', title: 'Drop an image here, or choose a file', text: 'PNG, JPEG, WEBP, SVG · max 10 MB', bd: '1px dashed var(--ui-border-accented)', bg: 'var(--ui-bg)' },
error: { icon: 'circle-x', ic: 'var(--ui-error)', title: 'Upload failed', text: 'The server didn\'t accept the file. Your article hasn\'t changed.', bd: '1px solid var(--ui-error)', bg: 'var(--ui-bg)' }
}
const up = upMap[U.state || 'idle'] || upMap.idle
let cr = {}
if (md.crop) {
const C = md.crop, IW = 4032, IH = 3024
const ri = C.ratio || 0, si = C.size ?? 1
const presets = [[0, 0, 100, 100], [6, 8, 88, 78], [0, 12.5, 100, 75], [0, 0, 100, 100], [12.5, 0, 75, 100]]
const r = C.rect || presets[ri]
const cw = Math.round(IW * r[2] / 100), ch = Math.round(IH * r[3] / 100)
const target = [cw, 1600, 1200, 800][si]
const ow = Math.min(target, cw), oh = Math.round(ch * ow / cw)
const kb = Math.round(ow * oh * 0.22 / 1000)
const pill = (pre, cur) => (t, i) => ({ t, on: i === cur, act: pre + i, bg: i === cur ? 'var(--ui-primary)' : 'transparent', fg: i === cur ? 'var(--ui-bg)' : 'var(--ui-text-toned)' })
cr = {
l: r[0] + '%', t: r[1] + '%', w: r[2] + '%', h: r[3] + '%', dims: fmt(cw) + ' × ' + fmt(ch),
ratios: ['Original', 'Free', '16:9', '4:3', '1:1'].map(pill('crop-r-', ri)),
sizes: ['Original', '1600 px', '1200 px', '800 px'].map(pill('crop-s-', si)),
out: 'Uploads as ' + fmt(ow) + ' × ' + fmt(oh) + ' px · about ' + (kb >= 1000 ? (kb / 1000).toFixed(1) + ' MB' : kb + ' KB'),
note: target > cw ? 'The crop is ' + cw + ' px wide, so it\'s uploaded at that size. Enlarging it would make it blurry.' : '',
stageH: m ? '240px' : '340px', pillFlex: m ? '1 1 0' : '0 0 auto', groupW: m ? '100%' : 'max-content'
}
}
const US = s.users || {}
const badges = { accepted: { t: 'Accepted', icon: 'circle-check', bg: 'var(--rc-success-soft)', fg: 'var(--ui-success)', bd: 'var(--rc-success-soft)' }, pending: { t: 'Pending', icon: 'mail', bg: 'var(--rc-warning-soft)', fg: 'var(--ui-warning)', bd: 'var(--rc-warning-soft)' }, expired: { t: 'Expired', icon: 'clock-alert', bg: 'transparent', fg: 'var(--ui-text-muted)', bd: 'var(--ui-border-accented)' } }
const roles = { owner: { t: 'owner', bg: 'var(--ui-primary)', fg: 'var(--ui-bg)', bd: 'var(--ui-primary)' }, admin: { t: 'admin', bg: 'transparent', fg: 'var(--ui-text-toned)', bd: 'var(--ui-border-accented)' } }
const acts = { pending: { key: 'cancel-invite', t: 'Cancel invite', icon: 'user-x', fg: 'var(--ui-error)', op: '1' }, expired: { key: 'renew-invite', t: 'Renew invite', icon: 'refresh-cw', fg: 'var(--ui-text-highlighted)', op: '1' } }
const usRows = (US.loading ? Array.from({ length: 5 }, () => ({ skel: true })) : (US.rows || [])).map(r => { if (r.skel) return r; const dn = (r.you && s.display) || r.display || ''; const a0 = acts[r.st]; return { ...r, dn: dn || '—', dfg: dn ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', display2: !!dn, fg: 'var(--ui-text-highlighted)', rl: roles[r.role] || roles.admin, b: badges[r.st] || badges.pending, bg: r.hl ? 'var(--ui-bg-elevated)' : 'transparent', act: a0 && (r.busy ? { ...a0, t: r.busy, icon: 'loader-circle', op: '0.5' } : a0) } })
const who = s.display || 'marta'
const ini = s.display ? s.display.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() : 'MA'
const pf = s.pf || {}
const dnVal = pf.value ?? s.display ?? ''
const dnLen = [...dnVal].length
const dn = { shown: dnVal || (pf.focus ? '' : 'e.g. Marta Alves'), caret: !!pf.focus, fg: pf.saving ? 'var(--ui-text-dimmed)' : dnVal ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', bd: pf.err ? 'var(--ui-error)' : pf.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)', sh: pf.err ? 'inset 0 0 0 1px var(--ui-error)' : pf.focus ? 'inset 0 0 0 1px var(--ui-primary)' : 'none', bg: pf.saving ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)', count: dnLen + ' / 60', countFg: dnLen > 60 ? 'var(--ui-error)' : 'var(--ui-text-muted)', err: pf.err || '', foot: pf.dirty && !pf.saving ? 'Unsaved changes' : 'You appear as \u201c' + who + '\u201d' + (s.display ? '.' : ', your username.'), footFg: pf.dirty && !pf.saving ? 'var(--ui-warning)' : 'var(--ui-text-muted)' }
const dnSave = { t: pf.saving ? 'Saving…' : 'Save', loading: !!pf.saving, op: pf.saving || (pf.dirty && !pf.err) ? '1' : '0.4' }
const rs = pf.reset || 'idle'
const rsMap = { sent: { bg: 'var(--rc-success-soft)', fg: 'var(--ui-success)', icon: 'mail-check', title: 'Reset link sent', text: 'Check marta@renew.example. The link works once, within 1 hour.' }, limited: { bg: 'var(--rc-warning-soft)', fg: 'var(--ui-warning)', icon: 'clock-alert', title: 'Too many requests', text: 'You\'ve asked for several links recently. Wait a few minutes, then try again.' }, error: { bg: 'var(--rc-error-soft)', fg: 'var(--ui-error)', icon: 'circle-x', title: 'Couldn\'t send the link', text: 'Check your connection and try again.' } }
const rsNote = rsMap[rs] || null
const rsBtn = { t: rs === 'sending' ? 'Sending…' : rs === 'sent' ? 'Send again' : 'Send reset link', icon: rs === 'sending' ? 'loader-circle' : 'mail', op: rs === 'limited' ? '0.4' : '1' }
const toasts = (s.toasts || []).map(t => ({ ...t, fg: 'var(--ui-' + t.tone + ')' }))
const endpoints = [
{ path: '/v1/article/', desc: 'Lists every online article.', l1: 'var(--ui-primary)', code: "const res = await fetch('https://cms.renew.example/v1/article/')\nconst articles = await res.json()" },
@@ -281,11 +422,16 @@ class Component extends DCLogic {
const edReady = k === 'editor' && !e.loading && !e.notfound
const edTitle = e.title || 'How we price a bathroom renovation'
return {
s, nav, crumbs, edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
desk: !m, mob: m, notBoot: !s.boot,
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
mLead: s.mLead || 'menu',
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isError: k === 'error',
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isError: k === 'error', isUsers: k === 'users',
usRows, usError: !!US.error, usOnly: !!US.only && !US.error, usTable: !m && !US.error, usCards: m && !US.error,
pad: m ? '20px 16px 88px' : '32px', gap: m ? '20px' : '28px', cols3: m ? 'repeat(3,minmax(0,1fr))' : 'repeat(3,minmax(0,1fr))',
btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px',
tbDir: m ? 'column' : 'row', tbGap: m ? '12px' : '16px', tbBorder: m ? '0' : '1px solid var(--ui-border)', tabBorder: m ? '1px solid var(--ui-border)' : '0', tabH: m ? '44px' : '36px', tabF: m ? '14px' : '13px',
@@ -302,7 +448,7 @@ class Component extends DCLogic {
saveOp: (dirty && !blocked) ? '1' : '0.4', imgCount: e.imgs != null ? String(e.imgs) : (e.image ? '4' : '3'), apiNote: online ? 'Live. Your website can read this article.' : 'Returns 404 until the article is online.',
copyIcon: s.copied ? 'check' : 'copy', copyText: s.copied ? 'Copied' : 'Copy', copyFg: s.copied ? 'var(--ui-success)' : 'var(--ui-text-highlighted)',
errPad: m ? '40px 20px' : '64px 48px',
modalAlign: m ? 'flex-end' : 'flex-start', modalPad: m ? '16px' : '140px 16px 16px', modalW: m ? '100%' : (md.wide ? '560px' : '460px'), mBtnDir: m ? 'column-reverse' : 'row',
modalAlign: m ? 'flex-end' : 'flex-start', modalPad: m ? '16px' : (md.crop ? '56px 16px 16px' : '140px 16px 16px'), modalW: m ? '100%' : (md.crop ? '640px' : md.wide ? '560px' : '460px'), mBtnDir: m ? 'column-reverse' : 'row',
mConfirmBg: md.tone === 'danger' ? 'var(--ui-error)' : 'var(--ui-primary)', mCancelFg: md.loading ? 'var(--ui-text-dimmed)' : 'var(--ui-text-highlighted)',
hasToasts: toasts.length > 0, tL: m ? '16px' : 'auto', tR: m ? '16px' : '24px', tB: m ? '16px' : '24px', tW: m ? 'auto' : '356px'
}
@@ -216,7 +216,7 @@
<span aria-live="polite" style="display:flex;align-items:center;gap:6px;color:var(--ui-warning)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-dot.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-dot.svg') center / contain no-repeat"></span>Unsaved changes</span>
<span style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat"></span>Save</span>
<span style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span>Save and publish</span>
<span style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat"></span></span>
<span role="button" aria-label="Delete article" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-error);color:var(--ui-error);font-weight:500;cursor:pointer"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat"></span>Delete</span>
</div>
<div role="toolbar" aria-label="Formatting" style="padding:6px 16px;display:flex;align-items:center;gap:2px;border-bottom:1px solid var(--ui-border);overflow-x:auto;background:var(--ui-bg)">
<sc-for list="{{ toolbar }}" as="t" hint-placeholder-count="24">
+7 -5
View File
@@ -16,8 +16,8 @@
<div data-screen-label="Emails" style="padding:64px;display:flex;flex-direction:column;gap:56px;width:max-content;min-width:100%">
<div style="display:flex;flex-direction:column;gap:10px;max-width:900px">
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:#111">Transactional emails</h1>
<p style="margin:0;font-size:16px;line-height:26px;color:#444;text-wrap:pretty">Two Go <code>html/template</code> files: <a href="emails/verification.html">emails/verification.html</a> and <a href="emails/password-reset.html">emails/password-reset.html</a>. They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and <code>prefers-color-scheme</code> overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values.</p>
<p style="margin:0;font-size:14px;line-height:22px;color:#666;text-wrap:pretty">Suggested subjects are "Verify your RenewCMS account" and "Reset your RenewCMS password". <code>html/template</code> escapes the <code>.Email</code> value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded.</p>
<p style="margin:0;font-size:16px;line-height:26px;color:#444;text-wrap:pretty">Three Go <code>html/template</code> files: <a href="emails/verification.html">emails/verification.html</a>, <a href="emails/password-reset.html">emails/password-reset.html</a> and <a href="emails/invitation.html">emails/invitation.html</a>. They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and <code>prefers-color-scheme</code> overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values.</p>
<p style="margin:0;font-size:14px;line-height:22px;color:#666;text-wrap:pretty">Suggested subjects are "Verify your RenewCMS account", "Reset your RenewCMS password" and "&lt;username&gt; invited you to RenewCMS", using <code>.InvitedBy</code>. <code>html/template</code> escapes the <code>.Email</code> value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded.</p>
</div>
<sc-for list="{{ rows }}" as="r" hint-placeholder-count="2">
<section style="display:flex;flex-direction:column;gap:20px">
@@ -33,13 +33,14 @@
</x-dc>
<script type="text/x-dc" data-dc-script>
class Component extends DCLogic {
state = { v: '', r: '' }
state = { v: '', r: '', i: '' }
componentDidMount() {
fetch('emails/verification.html').then(x => x.text()).then(v => this.setState({ v }))
fetch('emails/password-reset.html').then(x => x.text()).then(r => this.setState({ r }))
fetch('emails/invitation.html').then(x => x.text()).then(i => this.setState({ i }))
}
fill(t) {
return t.split('{{.Host}}').join('https://cms.renew.example').split('{{.VerificationCode}}').join('7f3c9a2e4b1d').split('{{.Email}}').join('marta%40renew.example').replace('uses marta%40renew.example', 'uses marta@renew.example')
return t.split('{{.InvitedBy}}').join('marta').split('{{.Email}} It').join('lea.martin@renew.example. It').split('sent to {{.Email}}').join('sent to lea.martin@renew.example').split('{{.Host}}').join('https://cms.renew.example').split('{{.VerificationCode}}').join('7f3c9a2e4b1d').split('{{.Email}}').join('marta%40renew.example').replace('uses marta%40renew.example', 'uses marta@renew.example')
}
frames(t) {
if (!t) return []
@@ -50,7 +51,8 @@ class Component extends DCLogic {
renderVals() {
return { rows: [
{ title: 'Verification email', vars: '{{.Host}} · {{.VerificationCode}} → /register/validate?c=', frames: this.frames(this.state.v) },
{ title: 'Password reset email', vars: '{{.Host}} · {{.VerificationCode}} · {{.Email}} → /register/reset/validate?c=&email=', frames: this.frames(this.state.r) }
{ title: 'Password reset email', vars: '{{.Host}} · {{.VerificationCode}} · {{.Email}} → /register/reset/validate?c=&email=', frames: this.frames(this.state.r) },
{ title: 'Invitation email', vars: '{{.Host}} · {{.VerificationCode}} · {{.Email}} · {{.InvitedBy}} → /invite/accept?c=', frames: this.frames(this.state.i) }
] }
}
}
+12 -5
View File
@@ -79,13 +79,14 @@ class Component extends DCLogic {
{ t: 'Foundations', d: 'Tokens, contrast, type, motion, icons', href: 'RenewCMS Foundations.dc.html' },
{ t: 'Primitives', d: 'Themed Nuxt UI components', href: 'RenewCMS Components Primitives.dc.html' },
{ t: 'Product components', d: '17 RenewCMS components', href: 'RenewCMS Components Product.dc.html' },
{ t: 'Auth screens', d: 'Six public routes, every state', href: 'RenewCMS Screens Auth.dc.html' },
{ t: 'Auth screens', d: 'Seven public routes, every state', href: 'RenewCMS Screens Auth.dc.html' },
{ t: 'Back-office screens', d: 'Verified routes and global states', href: 'RenewCMS Screens Back-office.dc.html' },
{ t: 'Emails', d: 'Previews of both templates', href: 'RenewCMS Emails.dc.html' },
{ t: 'Emails', d: 'Previews of the three templates', href: 'RenewCMS Emails.dc.html' },
{ t: 'tokens/renewcms.css', d: '@theme, :root, .dark, .article-content', href: 'tokens/renewcms.css' },
{ t: 'tokens/ui.config.ts', d: 'Nuxt UI colors, icons, overrides', href: 'tokens/ui.config.ts' },
{ t: 'tokens/vite.config.ts', d: 'Vite plugin setup', href: 'tokens/vite.config.ts' },
{ t: 'emails/verification.html', d: 'Go html/template', href: 'emails/verification.html' },
{ t: 'emails/invitation.html', d: 'Go html/template', href: 'emails/invitation.html' },
{ t: 'emails/password-reset.html', d: 'Go html/template', href: 'emails/password-reset.html' },
{ t: 'brand/favicon.svg', d: '16 px grid mark, dark-aware', href: 'brand/favicon.svg' }
]
@@ -95,6 +96,7 @@ class Component extends DCLogic {
['/register', 'AuthShell', 'public', 'RegisterPage', 'POST /v1/auth/register'],
['/register/pending', 'AuthShell', 'session', 'PendingPage', 'DELETE /v1/auth/register · POST /v1/auth/logout'],
['/register/validate', 'AuthShell', 'public', 'VerifyPage', 'POST /v1/auth/verify (+ POST /login inline on 401)'],
['/invite/accept', 'AuthShell', 'public', 'AcceptInvitePage', 'GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept*'],
['/register/reset/request', 'AuthShell', 'public', 'ResetRequestPage', 'POST /v1/auth/password-reset'],
['/register/reset/validate', 'AuthShell', 'public', 'ResetConfirmPage', 'POST /v1/auth/password-reset/confirm'],
['/home', 'DashboardShell', 'verified', 'HomePage', 'GET /v1/article/'],
@@ -120,9 +122,9 @@ class Component extends DCLogic {
['SaveStatus', 'custom (span + UButton)', "state: 'clean'|'dirty'|'saving'|'saved'|'error'|'offline', savedAt?: Date", 'retry', 'none', 'Editor'],
['PublishControl', 'UButton', 'online: boolean, dirty: boolean, pending?: string, disabled?', 'publish, unpublish', 'none', 'Editor'],
['ArticleDetails', 'UCard (desktop) / USlideover (mobile)', 'article: Article', 'copy-url', 'none', 'Editor'],
['CharacterCounter', 'custom', 'value: number, max: number, min?: number, warnAt?: number', 'none', 'none', 'NewArticleModal, Editor, Register'],
['PasswordStrengthHint', 'custom (in UFormField #help)', 'rules: { label, met }[], showErrors: boolean', 'none', 'none', 'Register, Reset'],
['ResultPanel', 'custom + UButton', "tone: 'success'|'error'|'info', icon, title, description, actions: ButtonProps[]", 'none', 'default', 'Pending, Verify, Reset request, Reset, Register (403)'],
['CharacterCounter', 'custom', 'value: number, max: number, min?: number, warnAt?: number', 'none', 'none', 'NewArticleModal, Editor, Register, Accept invite'],
['PasswordStrengthHint', 'custom (in UFormField #help)', 'rules: { label, met }[], showErrors: boolean', 'none', 'none', 'Register, Reset, Accept invite'],
['ResultPanel', 'custom + UButton', "tone: 'success'|'error'|'info', icon, title, description, actions: ButtonProps[]", 'none', 'default', 'Pending, Verify, Reset request, Reset, Accept invite, Register (403)'],
['CodeBlock', 'custom (shiki) + UButton', 'code: string, lang: string, label?', 'none', 'none', 'Integration'],
['EndpointCard', 'UCard, UBadge, UTabs', "method: 'GET', path, description, examples: { fetch, curl, response }", 'none', 'none', 'Integration'],
['ErrorView', 'custom + UButton', "kind: 'not-found'|'error'", 'retry', 'none', 'Not found, error boundary'],
@@ -136,6 +138,7 @@ class Component extends DCLogic {
M('Register', '/register', [['Default', 'Open instance'], ['Validation errors', 'Client rules fail'], ['Submitting', 'In flight'], ['Registration closed', '403'], ['Server error', '500 or network']]),
M('Pending', '/register/pending', [['Default', 'After registering (email known)'], ['Email unknown', 'After logging in unverified'], ['Confirm cancel', 'Cancel registration clicked'], ['Cancelling', 'DELETE in flight'], ['Cancelled', '200: /register with toast'], ['Already verified', '403: /home with toast']]),
M('Verify', '/register/validate?c=', [['Verifying', 'On load'], ['Success', '200: /home with toast'], ['Invalid or expired', '403'], ['No session', '401: inline log in, then retry'], ['Missing code', 'No c parameter']]),
M('Accept invite', '/invite/accept?c=', [['Checking the link', 'On load: GET invite*'], ['Default', 'Valid, unused code; email read-only'], ['Validation errors', 'Register rules fail'], ['Submitting', 'In flight'], ['Username taken', '409'], ['Invalid or used', '404 or no c parameter'], ['Expired', '410: ask the person who invited you'], ['Server error', '500 or network'], ['Success', '200: logged in, /home with toast']]),
M('Forgot password', '/register/reset/request', [['Default', 'Page load'], ['Validation', 'Invalid email'], ['Submitting', 'In flight'], ['Sent', 'Any 200 (neutral copy)'], ['Too many attempts', '429*'], ['Server error', '500 or network']]),
M('Reset password', '/register/reset/validate', [['Default', 'c and email present'], ['Too short', 'Under 8 characters'], ['Mismatch', 'Confirm field differs'], ['Submitting', 'In flight'], ['Success', '200: /login?reason=password-changed'], ['Invalid or expired', '403'], ['Missing parameters', 'No c or no email']]),
M('Home', '/home', [['Loading', 'List in flight (after 150 ms)'], ['Default', 'List loaded'], ['Empty', 'Zero articles'], ['Error', '500 or network']]),
@@ -153,6 +156,9 @@ class Component extends DCLogic {
['403', 'Any back-office call', 'Unverified: goes to /register/pending', 'Redirect'],
['403', 'Verify', '"This verification link doesn\'t work." Offers Cancel registration and start over', 'ResultPanel'],
['403', 'Cancel registration', '"Your account is already verified." Goes to /home', 'Toast'],
['404', 'Accept invite', '"This invite link doesn\'t work." Offers Go to log in', 'ResultPanel'],
['409', 'Accept invite', '"That username is taken. Try another."', 'Field'],
['410', 'Accept invite', '"This invite has expired. Ask the person who invited you to send a new one."', 'ResultPanel'],
['403', 'Reset confirm', '"This reset link has expired." Offers Request a new link', 'ResultPanel'],
['404', 'Editor load', '"This article doesn\'t exist." Offers All articles', 'ErrorView'],
['404', 'Row or editor action', '"That article no longer exists." The row is removed', 'Toast'],
@@ -167,6 +173,7 @@ class Component extends DCLogic {
const pending = [
{ a: 'GET /v1/auth/me → User | 401', d: 'The session check at boot. The HttpOnly cookie can\'t be read from JS. Until this exists, the guard can call GET /v1/article/ and infer: 401 means logged out, but verified and unverified users can\'t be told apart.' },
{ a: 'GET /v1/auth/registration → { open }', d: 'Shows "Create the owner account" on /login. Without it, the link is hidden and /register is reachable by URL only.' },
{ a: 'GET /v1/auth/invite?c=CODE → { email } | 404 | 410', d: 'Looks up the invite on load so the email can be shown and dead links are caught before the form. POST /v1/auth/invite/accept { code, username, password } returns 200 with the session cookie, 409 for a taken username, 404 or 410 as above. Neither exists yet.' },
{ a: '429 + Retry-After on /login, /password-reset', d: 'Drives the countdown state. The UI falls back to 60 s if the header is missing.' },
{ a: 'Serving /static/uploadedImages/*', d: 'The editor and preview are designed as if images load. Until they do, img tags show a broken image.' },
{ a: 'Not supported (disabled or omitted)', d: 'Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the password while logged in, editing the profile or email, listing or deleting individual images, multiple users.' }
+48 -5
View File
@@ -86,20 +86,32 @@ class Component extends DCLogic {
{ id: 6, t: 'Our first passive-house retrofit', on: true, c: '3 Apr 2026', u: '2 Jul 2026', imgs: 0 }
]
}
people() {
return [
{ email: 'sam.oliveira@renew.example', st: 'pending', c: '27 Sep 2026' },
{ email: 'p.huber@gmail.com', st: 'expired', c: '3 Aug 2026' },
{ u: 'ines', st: 'accepted', c: '18 Jun 2026' },
{ u: 'jonas', st: 'accepted', c: '2 Apr 2026' },
{ u: 'marta', st: 'accepted', c: '12 Mar 2026', you: true }
]
}
flowDefs = [
{ key: 'first', name: 'First run', desc: 'Register, verify by email, write and publish.', steps: [['register', 'Create the owner account'], ['pending', 'Check your email'], ['verified', 'Verify from the email'], ['firstArticle', 'Write the first article'], ['published', 'Publish it']], hints: { register: 'Click "Create account".', pending: 'Use "Open the verification email" below.', verified: 'Click "Verify my account" in the email.', firstArticle: 'Click "New article", then "Create draft".', published: 'Click "Publish" in the editor header.' } },
{ key: 'edit', name: 'Edit an article', desc: 'Log in, upload an image, save, unpublish.', steps: [['login', 'Log in'], ['openArticle', 'Open an article'], ['upload', 'Upload an image'], ['saved', 'Save'], ['unpublished', 'Unpublish']], hints: { login: 'Click "Log in".', openArticle: 'Go to Articles and click an online article.', upload: 'Click the image button at the end of the toolbar, then the drop area.', saved: 'Click "Save".', unpublished: 'Click "Unpublish".' } },
{ key: 'reset', name: 'Forgot password', desc: 'Request a link, reset, log in.', steps: [['forgot', 'Ask for a reset link'], ['email', 'Open the email'], ['changed', 'Choose a new password'], ['login', 'Log in']], hints: { forgot: 'Click "Forgot password?", then "Send reset link".', email: 'Use "Open the reset email" below, then click its button.', changed: 'Click "Change password".', login: 'Click "Log in".' } },
{ key: 'delete', name: 'Delete an article', desc: 'From the row menu, with confirmation.', steps: [['menu', 'Open the row menu'], ['confirm', 'Confirm the delete'], ['deleted', 'Article deleted']], hints: { menu: 'Click the ••• button on any row. On mobile, tap ⋮.', confirm: 'Choose "Delete…", then "Delete article".', deleted: '' } },
{ key: 'invite', name: 'Invite a user', desc: 'Give someone their own login instead of sharing yours.', steps: [['users', 'Go to Users'], ['form', 'Open the invite form'], ['taken', 'Try an address that\'s taken'], ['sent', 'Send the invite']], hints: { users: 'Click "Users" in the sidebar. On mobile, open the menu first.', form: 'Click "Invite user".', taken: 'Click "Send invite". The form fills with an address that already has an account.', sent: 'Click "Send invite" again. This time it uses a new address.' } },
{ key: 'expiry', name: 'Session expiry mid-edit', desc: 'Your unsaved work survives a new login.', steps: [['edited', 'Make a change'], ['expire', 'Session expires'], ['relogin', 'Log in again'], ['restored', 'Back in the editor, changes kept']], hints: { edited: 'Click the article text to make a change.', expire: 'Use "Simulate session expiry" below.', relogin: 'Click "Log in".', restored: '' } }
]
start(key) {
const articles = this.base()
const common = { flow: key, done: [], modal: null, menu: null, busy: null, toasts: [], auth: {}, mnav: false, expired: false, copied: false, email: null, ed: null, cur: null }
const users = key === 'first' ? this.people().slice(-1) : this.people()
const common = { users, flow: key, done: [], modal: null, menu: null, busy: null, toasts: [], auth: {}, mnav: false, expired: false, copied: false, email: null, ed: null, cur: null }
if (key === 'first') return { ...common, route: 'register', regOpen: true, articles: [] }
if (key === 'edit') return { ...common, route: 'login', regOpen: false, articles }
if (key === 'reset') return { ...common, route: 'login', regOpen: false, articles }
if (key === 'delete') return { ...common, route: 'articles', regOpen: false, articles }
if (key === 'invite') return { ...common, route: 'home', regOpen: false, articles }
return { ...common, route: 'editor', regOpen: false, articles, cur: 1, ed: { status: 'online', save: 'saved', image: false, preview: false } }
}
state = { device: 'desktop', mode: this.props.theme ?? 'light', hs: false, zoom: 1, emails: {}, ...this.start('first') }
@@ -174,8 +186,12 @@ class Component extends DCLogic {
}
act(a) {
const s = this.state
if (a === 'usermenu') return this.setState({ userMenu: !s.userMenu })
if (a && a.startsWith('theme-')) return this.setState({ mode: a.slice(6) })
if (s.userMenu) this.setState({ userMenu: false })
if (a === 'pf-reset') return this.setState({ pfReset: 'sent' })
if (a === 'mnav-close') return this.setState({ mnav: false })
if (a.startsWith('nav-')) return this.go(a.slice(4))
if (a.startsWith('nav-')) { const to = a.slice(4); if (to === 'users') this.mark('users'); return this.go(to) }
if (a === 'logout') { this.clearTimers(); this.setState({ route: 'login', auth: {}, mnav: false, menu: null, modal: null }); return this.toast('info', 'info', 'You\'re logged out', 'Log in again to keep working.') }
if (s.modal) return this.modalAct(a)
const r = s.route
@@ -221,6 +237,7 @@ class Component extends DCLogic {
}
return
}
if (a === 'invite') { this.mark('form'); return this.setState({ modal: { type: 'invite', tries: 0 }, menu: null }) }
if (a === 'new' || a === 'empty' || (a === 'm-action' && r === 'home')) return this.setState({ modal: { type: 'new' }, menu: null })
if (a === 'm-lead' && r !== 'editor') return this.setState({ mnav: true })
if (a.startsWith('open-')) return this.openEditor(Number(a.slice(5)))
@@ -279,6 +296,21 @@ class Component extends DCLogic {
}
return
}
if (m.type === 'invite') {
if (a === 'modal-cancel' || a === 'modal-close') return close()
if (a === 'modal-confirm') {
const taken = !m.tries
const email = taken ? 'jonas@renew.example' : 'lea.martin@renew.example'
this.setState({ modal: { ...m, email, err: null, loading: true } })
this.later(() => {
if (taken) { this.setState({ modal: { ...m, email, tries: 1, loading: false, err: 'This address already has an account.' } }); return this.mark('taken') }
this.setState(st => ({ modal: null, users: [{ email, st: 'pending', c: 'Today', hl: true }, ...st.users.map(u => ({ ...u, hl: false }))] }))
this.mark('sent')
this.toast('success', 'circle-check', 'Invite sent', email + ' has 3 days to accept.')
}, 900)
}
return
}
if (m.type === 'delete') {
if (a === 'modal-cancel' || a === 'modal-close') return close()
if (a === 'modal-confirm') {
@@ -294,7 +326,14 @@ class Component extends DCLogic {
return
}
if (m.type === 'upload') {
if (m.state === 'crop' && typeof a === 'string') {
if (a === 'modal-cancel') return this.setState({ modal: { ...m, state: 'idle' } })
if (a.startsWith('crop-r-')) return this.setState({ modal: { ...m, ratio: +a.slice(7) } })
if (a.startsWith('crop-s-')) return this.setState({ modal: { ...m, size: +a.slice(7) } })
if (a === 'crop-reset') return this.setState({ modal: { ...m, ratio: 0, size: 1 } })
}
if (a === 'modal-cancel' || a === 'modal-close') return close()
if (a === 'upload-pick' && m.state === 'idle') return this.setState({ modal: { ...m, state: 'crop', ratio: 0, size: 1 } })
if ((a === 'upload-pick' || a === 'modal-confirm') && m.state !== 'uploading') {
this.setState({ modal: { ...m, state: 'uploading' } })
this.later(() => {
@@ -331,10 +370,12 @@ class Component extends DCLogic {
const T = (name, crumb) => ({ nav: name, crumbs: crumb })
if (s.route === 'home') return { kind: 'home', ...T('home', ['Home']), mTitle: 'Home', mAction: 'plus', home: arts.length ? { sub: 'Here\'s where things stand on your site.', stats: [{ n: String(counts[0]), l: 'articles' }, { n: String(counts[1]), l: 'online' }, { n: String(counts[2]), l: 'drafts' }], recent: arts.slice(0, 5).map(a => ({ ...a, draft: !a.on })) } : { sub: 'Welcome to RenewCMS.', empty: true }, modal: this.modalS() }
if (s.route === 'articles') return { kind: 'articles', ...T('articles', ['Articles']), mTitle: 'Articles', list: { counts, rows: arts.map(a => ({ ...a, menu: s.menu === a.id, busy: s.busy === a.id ? (a.on ? 'Unpublishing…' : 'Publishing…') : null })), empty: arts.length ? null : { icon: 'file-text', title: 'No articles yet', text: 'Write your first one. It stays a draft until you publish it.', action: 'New article', primary: true } }, modal: this.modalS() }
if (s.route === 'users') return { kind: 'users', ...T('users', ['Users']), mTitle: 'Users', users: { rows: s.users, only: s.users.length === 1 }, modal: this.modalS() }
if (s.route === 'profile') return { kind: 'profile', ...T('profile', ['Profile']), mTitle: 'Profile', pf: { reset: s.pfReset } }
if (s.route === 'integration') return { kind: 'integration', ...T('integration', ['Integration']), mTitle: 'Integration', copied: s.copied }
if (s.route === 'editor') {
const a = this.art(s.cur) || {}, e = s.ed || {}
return { kind: 'editor', ...T('articles', ['Articles', a.t]), mTitle: 'Edit article', mLead: 'arrow-left', mAction: 'ellipsis', ed: { ...e, title: a.t, imgs: (a.imgs || 0) + (e.image ? 1 : 0) }, modal: this.modalS() }
return { kind: 'editor', ...T('articles', ['Articles', a.t]), mTitle: 'Edit article', mLead: 'arrow-left', mAction: 'trash-2', ed: { ...e, title: a.t, imgs: (a.imgs || 0) + (e.image ? 1 : 0) }, modal: this.modalS() }
}
return { kind: 'home', home: { sub: '' } }
}
@@ -342,11 +383,13 @@ class Component extends DCLogic {
const m = this.state.modal
if (!m) return null
if (m.type === 'new') return { title: 'New article', desc: 'It\'s saved as a draft. Titles can\'t be changed later, so check it now.', close: true, cancel: 'Cancel', confirm: m.loading ? 'Creating…' : 'Create draft', loading: m.loading, wide: true, fields: [{ label: 'Title', value: 'Choosing tiles for a small bathroom', count: '35 / 200', help: '3 to 200 characters.' }, { label: 'First paragraph', value: 'Small rooms show every grout line, so we start with the floor and work up.', area: true, help: 'You can format it and add images in the editor.' }] }
if (m.type === 'invite') return { title: 'Invite a user', desc: 'We\'ll email them a link to choose a username and password. The link expires after 3 days.', close: true, cancel: 'Cancel', confirm: m.loading ? 'Sending…' : 'Send invite', loading: m.loading, fields: [m.email ? { label: 'Email', value: m.email, err: m.err } : { label: 'Email', ph: 'name@example.com', focus: true }] }
if (m.type === 'delete') {
const a = this.art(m.id) || { t: '', imgs: 0 }
const imgs = a.imgs === 0 ? '' : a.imgs === 1 ? ' and its image' : ' and its ' + a.imgs + ' images'
return { title: 'Delete this article?', desc: '"' + a.t + '"' + imgs + ' will be deleted. This can\'t be undone.', cancel: 'Cancel', confirm: m.loading ? 'Deleting…' : 'Delete article', tone: 'danger', loading: m.loading }
}
if (m.type === 'upload' && m.state === 'crop') return { title: 'Crop and resize', desc: 'north-wall.jpg · 3.9 MB', close: true, crop: { ratio: m.ratio, size: m.size }, cancel: 'Choose another file', confirm: 'Upload image' }
if (m.type === 'upload') return { title: 'Add an image', close: true, upload: { state: m.state }, cancel: m.state === 'uploading' ? 'Cancel upload' : 'Cancel' }
if (m.type === 'leave') { const a = this.art(this.state.cur) || {}; return { title: 'Leave without saving?', desc: 'Your changes to "' + a.t + '" haven\'t been saved.', cancel: 'Discard changes', confirm: 'Keep editing' } }
return null
@@ -379,14 +422,14 @@ class Component extends DCLogic {
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const on = s.mode === k; return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) } })
const [dw, dh] = mobile ? [390, 844] : [1440, 900]
const navKey = s.route === 'editor' ? 'articles' : s.route
const mnavItems = [['nav-home', 'house', 'Home', 'home'], ['nav-articles', 'file-text', 'Articles', 'articles'], ['nav-integration', 'plug', 'Integration', 'integration'], ['logout', 'log-out', 'Log out', '']].map(([act, icon, t, k]) => ({ act, icon, t, bg: k && k === navKey ? 'var(--rc-sand)' : 'transparent', fg: k && k === navKey ? '#111111' : 'var(--ui-text-toned)' }))
const mnavItems = [['nav-home', 'house', 'Home', 'home'], ['nav-articles', 'file-text', 'Articles', 'articles'], ['nav-users', 'users', 'Users', 'users'], ['nav-integration', 'plug', 'Integration', 'integration'], ['logout', 'log-out', 'Log out', '']].map(([act, icon, t, k]) => ({ act, icon, t, bg: k && k === navKey ? 'var(--rc-sand)' : 'transparent', fg: k && k === navKey ? '#111111' : 'var(--ui-text-toned)' }))
const toasts = s.toasts.map(t => ({ ...t, fg: 'var(--ui-' + t.tone + ')' }))
return {
rootRef: this.rootRef, stageRef: this.stageRef,
devices: devs, modes, flows, hint, tools,
hs: s.hs, hsClass: s.hs ? 'hs' : '', hsJust: s.hs ? 'flex-end' : 'flex-start', hsBg: s.hs ? 'var(--ui-primary)' : 'var(--ui-bg-accented)', toggleHs: () => this.setState({ hs: !s.hs }),
mobile, isAuth, isApp, isEmail,
authS: isAuth ? this.authS() : {}, appS: isApp ? this.appS() : {},
authS: isAuth ? this.authS() : {}, appS: isApp ? { ...this.appS(), userMenu: s.userMenu, mode: s.mode } : {},
authBg: mobile ? 'var(--ui-bg)' : 'var(--ui-bg-muted)', authTop: mobile ? '40px' : '108px',
emailHtml: isEmail ? this.emailHtml() : '', emailSubject: s.email === 'reset' ? 'Reset your RenewCMS password' : 'Verify your RenewCMS account',
devW: dw + 'px', devH: dh + 'px', zoom: s.zoom, boxW: Math.round(dw * s.zoom) + 'px', boxH: Math.round(dh * s.zoom) + 'px',
@@ -18,7 +18,7 @@
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
<div style="flex:1;display:flex;flex-direction:column;gap:10px">
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screens: public and auth</h1>
<p style="margin:0;max-width:880px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Every state of the six public routes, at 1440 px (shown at 50%) and 390 px (shown at 75%). Use the switch on the right to see all of them in dark mode. Final copy is written into each state. The back-office screens and global states are on <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>, and the emails are on <a href="RenewCMS Emails.dc.html">the email board</a>.</p>
<p style="margin:0;max-width:880px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Every state of the seven public routes, at 1440 px (shown at 50%) and 390 px (shown at 75%). Use the switch on the right to see all of them in dark mode. Final copy is written into each state. The back-office screens and global states are on <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>, and the emails are on <a href="RenewCMS Emails.dc.html">the email board</a>.</p>
</div>
<div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)">
<sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
@@ -112,6 +112,8 @@ class Component extends DCLogic {
const loginF = (u, p) => [U(u), P({ link: 'Forgot password?', ...p })]
const reg = { title: 'Create the owner account', desc: 'This creates the single admin account for this site. Once it\'s verified, registration closes.', submit: { t: 'Create account' }, footer: { pre: 'Already set up?', link: 'Log in' } }
const regF = (u, e, p) => [U({ ph: 'e.g. marta', count: ((u && u.value) || '').length + ' / 20', help: 'Letters and numbers, 3 to 20 characters. You\'ll use it to log in.', ...u }), E({ help: 'We\'ll send a verification link here.', ...e }), P({ hints: pwHint('unmet'), ...p })]
const inv = { title: 'Accept your invite', desc: 'Choose a username and password to finish setting up your account.', submit: { t: 'Accept invite' }, footer: { pre: 'Already have an account?', link: 'Log in' } }
const invF = (u, p) => [E({ value: 'lea.martin@renew.example', ro: true, help: 'From your invitation.' }), U({ ph: 'e.g. lea', count: ((u && u.value) || '').length + ' / 20', help: 'Letters and numbers, 3 to 20 characters. You\'ll use it to log in.', ...u }), P({ hints: pwHint('unmet'), ...p })]
const pendingResult = email => ({ tone: 'success', icon: 'mail-check', title: 'Check your email', text: email ? 'We sent a verification link to ' + email + '. It expires in 2 hours.' : 'We sent a verification link to the email you registered with. It expires in 2 hours.', note: 'Opened it on another device? That works too; you\'ll log in there first. Can\'t find it? Check your spam folder. If the link has expired, cancel your registration and start again.', actions: [{ t: 'Log out', secondary: true }, { t: 'Cancel registration', secondary: true }] })
const cancelDialog = (loading) => ({ title: 'Cancel your registration?', text: 'Your account will be deleted. You can register again with the same or a different email.', confirm: loading ? 'Cancelling…' : 'Cancel registration', cancel: 'Keep my account' })
const reqBase = { title: 'Reset your password', desc: 'Enter the email for your account and we\'ll send you a link to choose a new password.', submit: { t: 'Send reset link' }, below: 'Back to log in' }
@@ -154,6 +156,18 @@ class Component extends DCLogic {
{ name: 'No session, retrying', trigger: 'Logged in inline. Now verifying.', spinner: 'Verifying your account…' },
{ name: 'Missing code', trigger: 'The link has no ?c= parameter. No request is made.', result: { tone: 'error', icon: 'link-2-off', title: 'This link is incomplete', text: 'The verification code is missing. Open the link from your email again, or copy the full address into your browser.', actions: [{ t: 'Go to log in', secondary: true }] } }
] },
{ label: 'Accept invite', title: 'Accept invite', route: '/invite/accept?c=CODE', api: 'GET /v1/auth/invite?c= (pending) · POST /v1/auth/invite/accept (pending)', note: 'Opened from the invitation email. The link carries only the code, so the invited email is looked up on load and shown read-only. Username and password follow the Register rules, including PasswordStrengthHint. On success the person is logged in and sent to /home with a toast; they are already verified because the invite went to their email.', states: [
{ name: 'Checking the link', trigger: 'On load, while the invite is looked up.', spinner: 'Checking your invite…' },
{ ...inv, name: 'Default', trigger: 'The code is valid and unused.', fields: invF({}, {}) },
{ ...inv, name: 'Validation errors', trigger: 'Checked on blur and on submit, using the same rules as Register. Nothing is sent.', fields: invF({ value: 'ma', err: 'Use 3 to 20 characters.', countErr: true, help: '' }, { value: 'lime', hints: pwHint('err') }) },
{ ...inv, name: 'Filled, valid', trigger: 'Every rule is met and the checklist item turns green.', fields: invF({ value: 'lea' }, { value: 'limewash2026', shown: true, hints: pwHint('met') }) },
{ ...inv, name: 'Submitting', trigger: 'Fields and button are disabled.', fields: invF({ value: 'lea' }, { value: 'limewash2026', hints: pwHint('met') }), submit: { t: 'Creating account…', loading: true } },
{ ...inv, name: 'Username taken (409)', trigger: 'Another user has that username. The value is kept and the field gets focus.', fields: invF({ value: 'marta', err: 'That username is taken. Try another.', focus: true, help: '' }, { value: 'limewash2026', hints: pwHint('met') }) },
{ name: 'Invalid or used link (404)', trigger: 'The code is wrong, was already accepted, or is missing from the URL. No form is shown.', result: { tone: 'error', icon: 'link-2-off', title: 'This invite link doesn\'t work', text: 'It may be incomplete, or it may already have been used. If you already set up your account, log in instead.', note: 'Open the link from your email again, or copy the full address into your browser.', actions: [{ t: 'Go to log in' }] } },
{ name: 'Expired link (410)', trigger: 'The invite is older than 3 days.', result: { tone: 'error', icon: 'clock', title: 'This invite has expired', text: 'Invites work once, for 3 days. Ask the person who invited you to send a new one.', actions: [{ t: 'Go to log in', secondary: true }] } },
{ ...inv, name: 'Server error', trigger: 'A 500 or no response. The values are kept.', notice: { tone: 'error', icon: 'circle-x', title: 'Couldn\'t create the account', text: 'Something went wrong on the server. Try again in a moment.' }, fields: invF({ value: 'lea' }, { value: 'limewash2026', hints: pwHint('met') }) },
{ name: 'Success', trigger: '200 sets the session cookie → /home after 800 ms, with a toast. No verification step.', result: { tone: 'success', icon: 'circle-check', title: 'Your account is ready', text: 'Taking you to your dashboard…', actions: [] }, toast: toast('success', 'circle-check', 'Welcome to RenewCMS', 'You\'re logged in as lea.') }
] },
{ label: 'Forgot password', title: 'Forgot password', route: '/register/reset/request', api: 'POST /v1/auth/password-reset', note: 'The sent state reads the same whether or not the email exists, so the page doesn\'t reveal which emails have accounts.', states: [
{ ...reqBase, name: 'Default', trigger: 'From "Forgot password?" on log in.', fields: [E()] },
{ ...reqBase, name: 'Validation error', trigger: 'Invalid email on submit. Nothing is sent.', fields: [E({ value: 'marta@renew', err: 'Enter a full email address, like name@example.com.' })] },
@@ -93,7 +93,20 @@ class Component extends DCLogic {
const nf = (title, body, extra = {}) => [{ label: 'Title', value: title, count: [...title].length + ' / 200', ...(extra.t || {}) }, { label: 'First paragraph', value: body, area: true, ...(extra.b || {}) }]
const ed = { kind: 'editor', nav: 'articles', crumbs: ['Articles', 'How we price a bathroom renovation'], mTitle: 'Edit article', mLead: 'arrow-left', mAction: 'ellipsis' }
const E = (o = {}, extra = {}) => withM({ ...ed, ...extra, ed: { status: 'draft', save: 'saved', ...o } })
const cropM = crop => ({ title: 'Crop and resize', desc: 'north-wall.jpg · 3.9 MB', close: true, crop, cancel: 'Choose another file', confirm: 'Upload image' })
const del = (loading, err) => ({ title: 'Delete this article?', desc: '"Winter checklist for timber windows" and its 3 images will be deleted. This can\'t be undone.', cancel: 'Cancel', confirm: loading ? 'Deleting…' : 'Delete article', tone: 'danger', loading, notice: err })
const people = [
{ email: 'sam.oliveira@renew.example', role: 'admin', st: 'pending', c: '27 Sep 2026' },
{ email: 'p.huber@gmail.com', display: 'Paul Huber', role: 'admin', st: 'expired', c: '3 Aug 2026' },
{ email: 'ines.duarte@renew.example', display: 'Inès Duarte', role: 'admin', st: 'accepted', c: '18 Jun 2026' },
{ email: 'jonas@renew.example', role: 'admin', st: 'accepted', c: '2 Apr 2026' },
{ email: 'marta@renew.example', role: 'owner', st: 'accepted', c: '12 Mar 2026', you: true }
]
const U = (o = {}) => ({ kind: 'users', nav: 'users', crumbs: ['Users'], mTitle: 'Users', ...o, users: { rows: people, ...(o.users || {}) } })
const inv = (o = {}) => ({ title: 'Invite a user', desc: 'We\'ll email them a link to choose a username and password. The link expires after 3 days.', close: true, cancel: 'Cancel', confirm: 'Send invite', ...o, fields: o.fields || [{ label: 'Email', ph: 'name@example.com', focus: true }] })
const invF = (value, extra = {}) => [{ label: 'Email', value, ...extra }]
const P = (pf = {}, o = {}) => withM({ kind: 'profile', nav: 'profile', crumbs: ['Profile'], mTitle: 'Profile', ...o, pf })
const dname = 'Marta Alves'
return [
{ label: 'Boot', title: 'App boot', route: 'any route, first load', api: 'GET /v1/auth/me (pending)', note: 'While the session is checked, the shell renders with skeletons, never a spinner. The possible outcomes are: 200 with a verified user, which renders the route; 200 with an unverified user, which goes to /register/pending; and 401, which goes to /login?redirect=<path>. Public routes skip this check.', states: [
withM({ ...home, name: 'Checking session', trigger: 'The first paint on any back-office URL, and usually visible for well under a second.', boot: true })
@@ -137,7 +150,10 @@ class Component extends DCLogic {
E({ save: 'dirty', len: 10214 }, { name: 'Too long', trigger: 'Over 10 000. Save and Publish are disabled until it\'s shorter.' }),
E({ preview: true }, { name: 'Preview', trigger: 'The Preview switch. Shows the title and body in the content scale, the way a public site might.' }),
E({ save: 'dirty' }, { name: 'Upload: choose', trigger: 'The image button in the toolbar, or a file dropped on the editor.', modal: { title: 'Add an image', close: true, upload: { state: 'idle' }, cancel: 'Cancel' } }),
E({ save: 'dirty' }, { name: 'Upload: in progress', trigger: 'A valid file is uploading. Closing the dialog cancels the upload.', modal: { title: 'Add an image', close: true, upload: { state: 'uploading' }, cancel: 'Cancel upload' } }),
E({ save: 'dirty' }, { name: 'Upload: crop and resize', trigger: 'A JPEG, PNG or WEBP passed the checks, and nothing is sent yet. The crop starts as the whole image and the width defaults to 1600 px. SVGs skip this step.', modal: cropM({ ratio: 0, size: 1 }) }),
E({ save: 'dirty' }, { name: 'Upload: crop to a ratio', trigger: '16:9 chosen. The frame keeps the ratio while it\'s dragged or resized. Arrow keys move it; Shift and arrow keys resize it.', modal: cropM({ ratio: 2, size: 1 }) }),
E({ save: 'dirty' }, { name: 'Upload: crop narrower than the width', trigger: 'The crop is smaller than the chosen width, so it keeps its own size.', modal: cropM({ ratio: 4, size: 1, rect: [42, 34, 15.873, 21.164] }) }),
E({ save: 'dirty' }, { name: 'Upload: in progress', trigger: 'Upload image was pressed. The cropped, resized file is uploading. Closing the dialog cancels the upload.', modal: { title: 'Add an image', close: true, upload: { state: 'uploading' }, cancel: 'Cancel upload' } }),
E({ save: 'dirty' }, { name: 'Upload: rejected', trigger: 'Checked in the browser, so nothing is sent.', modal: { title: 'Add an image', close: true, upload: { state: 'rejected' }, cancel: 'Cancel', confirm: 'Choose another file' } }),
E({ save: 'dirty', image: true }, { name: 'Upload: inserted', trigger: '201: the image goes in at the cursor, and the article now has unsaved changes.', toasts: [T('success', 'circle-check', 'Image added', 'Save to keep it in the article.')] }),
E({ save: 'saving', pending: 'Saving and publishing…' }, { name: 'Publishing', trigger: '"Save and publish": the PATCH body, then the publish request.' }),
@@ -152,6 +168,43 @@ class Component extends DCLogic {
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }),
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', copied: true, name: 'Copied', trigger: 'The base URL was copied. The button reads "Copied" for 2 s and this is announced.' })
] },
{ label: 'Users', title: 'Users', route: '/users', api: 'GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id (pending) · POST /v1/user/invite/:id/renew (pending)', note: 'One shared workspace: every user sees the same articles and this same list. Columns: email, display name, role (owner or admin), invite status and created date. A pending invite can be cancelled and an expired one renewed; accepted accounts have no row actions. An invite is Pending until its link is used, Expired after 3 days, and Accepted once the account is created.', states: [
withM({ ...U(), name: 'Default', trigger: 'The list loaded, newest first.' }),
withM({ ...U({ users: { loading: true } }), name: 'Loading', trigger: 'The first load, or a retry. Skeletons appear after 150 ms.' }),
withM({ ...U({ users: { rows: people.slice(-1), only: true } }), name: 'Only you', trigger: 'Nobody has been invited yet. The admin who registered is always listed.' }),
withM({ ...U({ users: { error: true } }), name: 'Error', trigger: 'A 500 or network failure on the list request.' }),
withM({ ...U({ modal: inv() }), name: 'Invite: default', trigger: '"Invite user" in the page header, or the bottom button on mobile.' }),
withM({ ...U({ modal: inv({ fields: invF('sam.oliveira@renew', { err: 'Enter a full email address, like name@example.com.' }) }) }), name: 'Invite: validation', trigger: 'On submit or blur. Nothing is sent.' }),
withM({ ...U({ modal: inv({ loading: true, confirm: 'Sending…', fields: invF('lea.martin@renew.example') }) }), name: 'Invite: sending', trigger: 'Request in flight. The field is disabled and the dialog can\'t be dismissed.' }),
withM({ ...U({ modal: inv({ fields: invF('jonas@renew.example', { err: 'This address already has an account.' }) }) }), name: 'Invite: already a user (409)', trigger: 'The email belongs to an existing user. For a live pending invite the message reads "There\'s already a pending invite for this address." An expired invite can be sent again.' }),
withM({ ...U({ modal: inv({ notice: 'Couldn\'t send the invite. Try again in a moment.', fields: invF('lea.martin@renew.example') }) }), name: 'Invite: failed', trigger: '500, network failure, or the email couldn\'t be sent. The address stays in the field.' }),
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancel invite', tone: 'danger' } }), name: 'Cancel invite: confirm', trigger: '"Cancel invite" on a Pending row.' }),
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancelling…', tone: 'danger', loading: true } }), name: 'Cancel invite: sending', trigger: 'Request in flight. Both buttons are disabled.' }),
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancel invite', tone: 'danger', notice: 'Couldn\'t cancel the invite. Try again in a moment.' } }), name: 'Cancel invite: failed', trigger: '500 or network failure. The dialog stays open.' }),
withM({ ...U({ users: { rows: people.slice(1) }, toasts: [T('success', 'circle-check', 'Invite cancelled', 'sam.oliveira@renew.example can no longer use the link.')] }), name: 'Cancel invite: done', trigger: '204: the row disappears and a toast confirms.' }),
withM({ ...U({ users: { rows: people.map(p => p.st === 'expired' ? { ...p, busy: 'Renewing…' } : p) } }), name: 'Renew invite: sending', trigger: '"Renew invite" on an Expired row. No confirmation, since it only sends an email. The button shows progress and is disabled.' }),
withM({ ...U({ users: { rows: [{ ...people[1], st: 'pending', c: 'Today', hl: true }, ...people.filter((p, i) => i !== 1)] }, toasts: [T('success', 'circle-check', 'Invite renewed', 'p.huber@gmail.com has 3 days to accept the new link.')] }), name: 'Renew invite: done', trigger: '200: the row becomes Pending with today\'s date, moves to the top, and the old link stops working.' }),
withM({ ...U({ toasts: [T('error', 'circle-x', 'Couldn\'t renew the invite', 'Try again in a moment.')] }), name: 'Renew invite: failed', trigger: '500 or network failure. The row stays Expired and the button can be pressed again.' }),
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', role: 'admin', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
] },
{ label: 'Settings', title: 'Settings', route: '/settings', api: 'none (static)', note: 'Opened from the sidebar. For now it holds only the Version section.', states: [
withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', name: 'Default', trigger: 'Opened from the sidebar.' })
] },
{ label: 'Profile', title: 'Profile', route: '/profile', api: 'GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset', note: 'Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters. Once saved it replaces the username everywhere a person is named: the sidebar, the account menu, the Home greeting, the Users list (with the username beside it) and the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS". Saving it empty goes back to the username. The reset link uses the same flow as "Forgot password" and ends on the auth board\'s "Choose a new password" screen.', states: [
withM({ ...home, home: { sub: 'Here\'s where things stand on your site.', stats, recent }, userMenu: true, name: 'Account menu', trigger: 'The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.' }),
P({ loading: true }, { name: 'Loading', trigger: 'Opened directly by URL before /auth/me has returned. From the menu, the cached user renders straight away.' }),
P({}, { name: 'Default, no display name', trigger: 'The usual first visit. The username is used everywhere.' }),
P({ value: dname, focus: true, dirty: true }, { name: 'Editing', trigger: 'Typing in the field. Save turns on, and leaving the page asks for confirmation.' }),
P({ value: 'Marta Alves, Head of Renovations, Brussels and Wallonia office', focus: true, dirty: true, err: 'Use 60 characters or fewer.' }, { name: 'Too long', trigger: 'Over 60 characters. Checked as you type, and Save stays off.' }),
P({ value: dname, dirty: true, saving: true }, { name: 'Saving', trigger: 'Save, or Enter in the field. The field is disabled.' }),
P({}, { display: dname, name: 'Saved', trigger: '200: the sidebar and account menu switch to the display name at once, and a toast confirms.', toasts: [T('success', 'circle-check', 'Display name saved', 'You now appear as Marta Alves across RenewCMS and in emails.')] }),
P({ value: dname, dirty: true, notice: 'Couldn\'t save your display name. Your text is still here. Try again in a moment.' }, { name: 'Save failed', trigger: '500 or network failure. The typed value is kept.' }),
P({ reset: 'sending' }, { display: dname, name: 'Reset: sending', trigger: '"Send reset link". No confirmation, since it only sends an email.' }),
P({ reset: 'sent' }, { display: dname, name: 'Reset: sent', trigger: '200. The message stays until the page is left. "Send again" sends a new link and the old one stops working.' }),
P({ reset: 'limited' }, { display: dname, name: 'Reset: too many requests (429)', trigger: 'Rate limited. The button is disabled for 5 minutes.' }),
P({ reset: 'error' }, { display: dname, name: 'Reset: failed', trigger: '500 or network failure. The button can be pressed again.' }),
withM({ ...U(), display: dname, name: 'Display names in the Users list', trigger: 'The Display name column shows the name when one is set and a dash when not. Your own row follows your saved name.' })
] },
{ label: 'Global', title: 'Global states', route: 'any route', api: '', note: 'A 401 on any back-office call redirects to /login?redirect=<path>&reason=expired (see "Session expired" on the auth board). A 403 from an unverified account redirects to /register/pending. A 429 appears only on log in and password reset. Toasts sit bottom right on desktop and bottom center on mobile, at most 3 at once. Success and info last 5 s; errors stay until dismissed.', states: [
withM({ kind: 'error', nav: '', crumbs: ['Not found'], mTitle: 'Not found', name: '404 inside the shell', trigger: 'An unknown route while logged in. Logged out, the same content appears inside AuthShell.', err: { code: '404', title: 'Page not found', text: 'The link may be mistyped, or the page may have moved.', primary: 'Go to Home', secondary: 'All articles' } }),
withM({ kind: 'error', nav: 'home', crumbs: ['Home'], mTitle: 'Home', name: 'Generic error', trigger: 'An unexpected error while rendering a route.', err: { code: 'Error', title: 'Something went wrong', text: 'This page couldn\'t load. Your saved work is safe. Try again, and if it keeps happening, restart the RenewCMS server.', primary: 'Try again', secondary: 'Go to Home' } }),
+72
View File
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<meta name="supported-color-schemes" content="light dark">
<title>You're invited to RenewCMS</title>
<style>
body { margin: 0; padding: 0; width: 100%; -webkit-text-size-adjust: 100%; }
table { border-collapse: collapse; }
a { color: #111111; }
@media (max-width: 620px) {
.rc-card { padding: 28px 20px !important; }
.rc-btn a { display: block !important; }
}
@media (prefers-color-scheme: dark) {
.rc-bg { background-color: #0a0a0a !important; }
.rc-card { background-color: #111111 !important; border-color: #333333 !important; }
.rc-h1, .rc-word { color: #fafafa !important; }
.rc-text { color: #e6e4e0 !important; }
.rc-muted { color: #999999 !important; }
.rc-mark { border: 1px solid #444444 !important; }
.rc-btn td { background-color: #fafafa !important; }
.rc-btn a { background-color: #fafafa !important; color: #111111 !important; border-color: #fafafa !important; }
.rc-url { color: #e6e4e0 !important; background-color: #1a1a1a !important; }
.rc-rule { border-color: #333333 !important; }
}
</style>
</head>
<body class="rc-bg" style="margin:0;padding:0;background-color:#fafafa;">
<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;">{{.InvitedBy}} invited you to work on articles in RenewCMS. The invite expires in 3 days.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="rc-bg" style="background-color:#fafafa;">
<tr>
<td align="center" style="padding:40px 12px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;">
<tr>
<td style="padding:0 0 20px 0;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="rc-mark" width="32" height="32" align="center" valign="middle" bgcolor="#111111" style="width:32px;height:32px;background-color:#111111;color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:19px;font-weight:bold;line-height:32px;">R</td>
<td class="rc-word" style="padding-left:10px;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:17px;font-weight:600;color:#111111;">RenewCMS</td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="rc-card" style="background-color:#ffffff;border:1px solid #e6e4e0;padding:40px;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;">
<h1 class="rc-h1" style="margin:0 0 16px 0;font-size:24px;line-height:32px;font-weight:600;color:#111111;">You're invited to RenewCMS</h1>
<p class="rc-text" style="margin:0 0 28px 0;font-size:16px;line-height:26px;color:#222222;">{{.InvitedBy}} invited you to write and publish articles in RenewCMS at {{.Host}}. Accept to choose a username and password. You'll sign in with your own account.</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" class="rc-btn">
<tr>
<td bgcolor="#111111" style="background-color:#111111;">
<a href="{{.Host}}/invite/accept?c={{.VerificationCode}}" target="_blank" style="display:inline-block;padding:14px 24px;border:1px solid #111111;background-color:#111111;color:#ffffff;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:16px;font-weight:600;line-height:20px;text-decoration:none;text-align:center;">Accept invite</a>
</td>
</tr>
</table>
<p class="rc-muted" style="margin:16px 0 0 0;font-size:14px;line-height:22px;color:#666666;">This invite was sent to {{.Email}}. It expires in 3 days and works once.</p>
<p class="rc-muted" style="margin:28px 0 8px 0;font-size:14px;line-height:22px;color:#666666;">If the button doesn't work, copy this address into your browser:</p>
<p class="rc-url" style="margin:0;padding:10px 12px;background-color:#f3f2f0;font-family:'IBM Plex Mono',Menlo,Consolas,monospace;font-size:13px;line-height:20px;color:#222222;word-break:break-all;">{{.Host}}/invite/accept?c={{.VerificationCode}}</p>
<p class="rc-text rc-rule" style="margin:28px 0 0 0;padding-top:20px;border-top:1px solid #e6e4e0;font-size:14px;line-height:22px;color:#222222;">Not expecting this? Ignore this email and no account will be created. If the invite has expired, ask {{.InvitedBy}} to send a new one.</p>
</td>
</tr>
<tr>
<td class="rc-muted" style="padding:20px 0 0 0;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:12px;line-height:18px;color:#666666;">RenewCMS · {{.Host}}</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
+55 -3
View File
@@ -74,7 +74,7 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
| Editor | `/article/:id/edit` | Near the limit | At least 9 000 HTML characters | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Too long | Over 10 000: Save and Publish disabled | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Preview | Switch on | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Uploading, rejected, inserted | ImageUploader | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Choose, crop and resize, uploading, rejected, inserted | ImageUploader | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Publishing, unpublishing | PATCH publish or unpublish | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Leave guard | Navigating away while dirty | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Offline | navigator.onLine is false | [editor](screens/editor.md) |
@@ -82,6 +82,33 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
| Editor | `/article/:id/edit` | Session expired | 401: draft kept in sessionStorage, then /login | [editor](screens/editor.md) |
| Integration | `/integration` | Default | Page load | [integration](screens/integration.md) |
| Integration | `/integration` | Copied | Copy clicked (2 s) | [integration](screens/integration.md) |
| Users | `/users` | Default | List loaded, newest first | [users](screens/users.md) |
| Users | `/users` | Loading | First load or retry | [users](screens/users.md) |
| Users | `/users` | Only you | Nobody invited yet | [users](screens/users.md) |
| Users | `/users` | Error | 500 or network | [users](screens/users.md) |
| Users | `/users` | Invite: default, validation, sending | Invite modal opened, invalid email, POST in flight | [users](screens/users.md) |
| Users | `/users` | Invite: already a user | 409 | [users](screens/users.md) |
| Users | `/users` | Invite: failed | 500, network or mail failure | [users](screens/users.md) |
| Users | `/users` | Invite sent | 201: dialog closes, Pending row on top, toast | [users](screens/users.md) |
| Users | `/users` | Cancel invite: confirm, sending, failed | "Cancel invite" on a Pending row; DELETE in flight; 500 or network | [users](screens/users.md) |
| Users | `/users` | Cancel invite: done | 204: row removed, toast | [users](screens/users.md) |
| Users | `/users` | Renew invite: sending | "Renew invite" on an Expired row; POST in flight | [users](screens/users.md) |
| Users | `/users` | Renew invite: done | 200: row Pending on top, toast | [users](screens/users.md) |
| Users | `/users` | Renew invite: failed | 500 or network: toast, row stays Expired | [users](screens/users.md) |
| Settings | `/settings` | Default | Opened from the sidebar | [settings](screens/settings.md) |
| Profile | `/profile` | Account menu | Account chip clicked | [profile](screens/profile.md) |
| Profile | `/profile` | Loading | Opened by URL before /auth/me returns | [profile](screens/profile.md) |
| Profile | `/profile` | Default, no display name | First visit | [profile](screens/profile.md) |
| Profile | `/profile` | Editing, too long | Typing; over 60 characters | [profile](screens/profile.md) |
| Profile | `/profile` | Saving, saved, save failed | PATCH in flight, 200, 500 or network | [profile](screens/profile.md) |
| Profile | `/profile` | Reset: sending, sent, 429, failed | POST /v1/auth/password-reset | [profile](screens/profile.md) |
| Profile | `/profile` | Display names in the Users list | Accounts with a display name | [profile](screens/profile.md) |
| Accept invite | `/invite/accept?c=` | Checking the link | On load: GET invite | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Default, validation errors, filled, submitting | Valid, unused code; email read-only | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Username taken | 409 | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Invalid or used, expired | 404 or no c parameter, 410 | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Server error | 500 or network | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Success | 200: logged in, /home with toast | [accept-invite](screens/accept-invite.md) |
## HTTP status to copy
@@ -98,18 +125,43 @@ Response bodies are plain text and are never shown. `useApi` throws an `ApiError
| 403 | Verify | "This verification link doesn't work." Offers Cancel registration and start over | ResultPanel |
| 403 | Cancel registration | "Your account is already verified." Goes to /home | Toast |
| 403 | Reset confirm | "This reset link has expired." Offers Request a new link | ResultPanel |
| 409 | Invite | "This address already has an account." or, for a live invite, "There's already a pending invite for this address." | Field error |
| 404 | Accept invite | "This invite link doesn't work." Offers Go to log in | ResultPanel |
| 409 | Accept invite | "That username is taken. Try another." | Field |
| 410 | Accept invite | "This invite has expired. Ask the person who invited you to send a new one." | ResultPanel |
| 404 | Editor load | "This article doesn't exist." Offers All articles | ErrorView |
| 404 | Row or editor action | "That article no longer exists." The row is removed | Toast |
| 404 | Unknown route | "Page not found" | ErrorView |
| 429 | Profile, reset link | "Too many requests. You've asked for several links recently. Wait a few minutes, then try again." Button disabled | Note |
| 429 | Log in, reset request | "Too many attempts. For your security, wait a moment before trying again." With a countdown | Alert + disabled button |
| 500 | Save | "Save failed" + Retry. Changes are kept | SaveStatus |
| 500 | Publish / unpublish | "Couldn't publish" / "Couldn't unpublish" + Retry | Toast |
| 500 | Load users | "Couldn't load users. Check your connection and try again." + Try again | Alert |
| 500 | Cancel invite | "Couldn't cancel the invite. Try again in a moment." The dialog stays open | Notice in dialog |
| 500 | Renew invite | "Couldn't renew the invite. Try again in a moment." The row stays Expired | Toast |
| 500 | Invite | "Couldn't send the invite. Try again in a moment." The address stays | Alert in dialog |
| 500 | Save display name | "Couldn't save your display name. Your text is still here. Try again in a moment." | Alert in card |
| 500 | Send reset link (profile) | "Couldn't send the link. Check your connection and try again." | Note |
| 500 | Delete | "Couldn't delete the article, so it's still there. Try again in a moment." | Inline in dialog |
| 500 | Upload | "Upload failed. The server didn't accept the file. Your article hasn't changed." | ImageUploader |
| network | Anywhere | "Couldn't reach RenewCMS. Check your connection and try again." Offline: banner | Alert / toast / banner |
## API the design marked pending
All four now exist: `GET /v1/auth/me`, `GET /v1/auth/registration`, `429` with `Retry-After` on `/v1/auth/login` and `/v1/auth/password-reset`, and `/static/uploadedImages/*`. Still not supported, so shown disabled or omitted:
Existing: `GET /v1/auth/me`, `GET /v1/auth/registration`, `429` with `Retry-After` on `/v1/auth/login` and `/v1/auth/password-reset`, and `/static/uploadedImages/*`.
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the password while logged in, editing the profile or email, listing or deleting individual images, multiple users.
Added by the Users and Profile screens, none of which exist yet:
- `GET /v1/user/`: the users and their invites, newest first.
- `POST /v1/user/invite`: sends an invitation email. 201, 409 for an existing account or a live pending invite.
- `DELETE /v1/user/invite/:id`: cancels a Pending invite. 204. Owner only.
- `POST /v1/user/invite/:id/renew`: replaces the code, resets the 3 days and created date, and resends the email. 200 with the invite. Owner only.
- `GET /v1/user/` and `GET /v1/auth/me` gain a `role` ("owner" or "admin"); the list gains `email` on accepted users.
- `POST /v1/user/invite` becomes owner only, and always creates an admin.
- `GET /v1/settings`: `{ "version": "..." }`.
- `PATCH /v1/user/me`: saves the display name. `GET /v1/auth/me` returns it.
- `GET /v1/auth/invite?c=CODE`: looks up the invite on load, returns `{ email }`, 404 or 410. `POST /v1/auth/invite/accept` takes `{ code, username, password }` and returns 200 with the session cookie, 409 for a taken username, 404 or 410.
Still not supported, so shown disabled or omitted:
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the email or username, listing or deleting individual images, removing users, promoting or demoting anyone, and any role other than owner and admin. Changing the password while logged in works only through the emailed reset link on the Profile page.
+28
View File
@@ -0,0 +1,28 @@
# Release notes format
Name: `vX.Y.Z-beta - Short theme` (theme is 2 to 6 words, sentence case).
Tag: `vX.Y.Z-beta`, always with the `v`.
Body, in this order. Omit a section only when it would be empty, except Upgrading, which is always present.
1. Intro: one or two plain sentences on what the release is about. No heading.
2. `## New`: user-visible features. Group with a bold title line (`**Group name**`) followed by bullets.
3. `## Improvements and fixes`: flat bullets.
4. `## API`: one bullet per endpoint change, `METHOD /v1/path` in backticks, then behaviour and status codes. Prefix breaking or shape changes with "Changed:".
5. `## Under the hood`: dependencies, tests, docs, architecture. Only when relevant to contributors.
6. `## Upgrading`: binary replacement, schema/migration changes, new env vars, behaviour changes for existing installs.
7. `## Known limitations`: only when there are real ones.
Rules: bullets are full sentences ending with a period; user-facing wording, no commit prefixes; sentence-case headings; no horizontal rules, no metadata block, no "Pre-1.0" boilerplate (the prerelease flag says it); every release ships all 6 binaries from `task release`.
## Published releases
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <binary>` (one `--asset` per binary), after `task release`.
| Tag | Name |
| --- | --- |
| `2.0.0-beta` (legacy tag without the `v`, kept as is) | v2.0.0-beta - Vue 3 SPA and domain-driven backend |
| `v2.1.0-beta` | v2.1.0-beta - Image upload in the editor |
| `v2.2.0-beta` | v2.2.0-beta - Image crop, image removal & reset screens |
| `v2.3.0-beta` | v2.3.0-beta - Multi-user invitations, display names & profile page |
| `v2.4.0-beta` | v2.4.0-beta - Owner role, invite management & Settings page |
+28
View File
@@ -0,0 +1,28 @@
A ground-up rewrite of RenewCMS's backend architecture and frontend. The Go-template UI is replaced by a Vue 3 single-page app embedded in the same binary.
## New
**Vue 3 single-page app**
- Built with Vite, Pinia and vue-router, and embedded into the single binary. There is no separate frontend deployment.
- The UI uses Nuxt UI (migrated from an initial PrimeVue base) with shared design tokens.
- New screens: login, registration, home and navigation, article list, article editor (ProseMirror-based) with a creation modal, image upload, and an account and integration screen.
- A typed API client and a session store handle 401, unverified 403, 429 and offline states the same way everywhere.
**Domain-driven backend**
- `internal/domain` (entities, sentinel errors, repository interfaces) is isolated from persistence (GORM), mailer and API concerns, with a strict inward dependency rule.
- Business logic moved out of handlers and the persistence layer into use cases: article rules, image validation, password and code hashing, not-found handling, and session invalidation on password reset.
- The composition root (`api/dependecyInjection.go`) wires the database, repositories and use cases explicitly. Runtime settings are read once at startup.
- The auth handler is split into dedicated registration, login, verification and password-reset handlers, each with per-client rate limiting on the public routes.
## Improvements and fixes
- API responses no longer leak password hashes, verification or reset code hashes, or their expiry dates.
- Article read rules now apply the same way to the single-article and list endpoints: the public sees online articles only, verified users also see offline ones.
- Registration only opens when no verified account exists, and deleting a user frees its username and email for reuse.
- Rate limiting now keys off the real peer IP.
## Under the hood
- Use cases are covered by a full in-memory fake test suite with clean gremlins mutation coverage.
- Vitest and Vue Test Utils run the frontend tests, and an automated visual-parity check compares the app to the design source boards.
## Upgrading
- Deployment is unchanged: a single binary, systemd and a reverse proxy. Replace the binary and restart.
+20
View File
@@ -0,0 +1,20 @@
This release adds image upload to the article editor and fixes several rough edges from v2.0.0-beta.
## New
**Image upload in the article editor**
- The editor's Image toolbar button, or dropping a file onto the editor, opens an upload dialog.
- Choose or drop a PNG, JPEG, WEBP or SVG file up to 10 MB. Progress is shown live, and the image is inserted at the cursor as soon as it is uploaded.
- Invalid files (wrong type or too large) are rejected in the browser before anything is sent. The same wording is reused if the server rejects a file the browser let through.
- A failed upload leaves the article untouched and offers a retry.
## Improvements and fixes
- Uploaded images now render in the editor and the article body. The dev server proxy was missing a route for the endpoint that serves them.
- Clicking a row in the article list now opens the editor. The row-click handler was reading the wrong argument.
- The article details panel's copy URL control now copies the link and confirms with a toast.
- The user menu's dropdown trigger no longer misrenders when the sidebar is collapsed.
- The sidebar's collapsed or expanded state is remembered across reloads.
- Smaller styling and layout fixes in the article details panel, editor toolbar and new-article dialog.
## Upgrading
- Replace the binary and restart.
+32
View File
@@ -0,0 +1,32 @@
This release reworks image handling in the article editor and brings the password-reset screens up to the new design.
## New
**Crop and resize before upload**
- A Crop and resize step now sits between picking an image and uploading it. It applies to JPEG, PNG and WEBP files. SVG files still upload straight away.
- Move or resize the crop frame by dragging it or its handles. Arrow keys nudge it by 1 px, and Shift+arrow resizes it by 1 px.
- Aspect ratios: Original, Free, 16:9, 4:3 and 1:1.
- Rotate and Reset buttons.
- Output width presets: Original, 1600 px (default), 1200 px and 800 px. The output is never wider than the crop frame.
- A live line shows the final pixel size and an approximate file size before you upload.
**Remove images from the editor**
- Images in an article can now be removed from the editor. The image file and its database row are both deleted.
- The editor renders images as a dedicated image node.
**Password-reset screens**
- The Forgot password and Reset password screens follow the new design and cover every state in the spec.
## API
- `DELETE /v1/article/{id}/image/{imageId}` (authenticated) deletes an image. It returns 204 on success, 404 for an unknown article or image, and 400 for an ID that isn't a valid uint32.
- Changed: `POST /v1/article/{id}/image` now returns `{"id": …, "location": …}` instead of `{"location": …}`. The change is additive, but anything parsing the response strictly should be checked.
## Under the hood
- The editor now depends on `@tiptap/extension-image`, `@tiptap/pm` and `@tiptap/vue-3`, all pinned to 3.31.3.
- New feature specs and QA procedures cover crop and resize, image removal and both reset screens.
- New Go HTTP tests cover image deletion, and Vitest specs were added and updated for the editor and reset views.
- The visual-check states cover the new screens, and the design docs are updated to match.
## Upgrading
- No new environment variables and no schema changes.
- Replace the binary and restart.
+43
View File
@@ -0,0 +1,43 @@
RenewCMS is no longer a one-person tool. The admin can now invite other people, each with their own account and the exact same access, and everyone can set a display name.
## New
**Invite other users**
- A new Users page in the back-office lists everyone who can sign in, plus pending and expired invites, with a status badge for each.
- Invite user sends an email with a personal link. The link works once and expires after 3 days.
- Invited people choose their own username and password on a new Accept invite screen, and land on Home already logged in.
- Everyone shares one workspace: same articles, same images, same access.
- Registration stays closed to everyone who wasn't invited.
- A new invitation email template supports light and dark mode.
**Display name and profile**
- A new Profile page is opened from the account menu at the bottom of the sidebar.
- Set an optional display name (up to 60 characters). It replaces your username in the sidebar, the account menu, the Home greeting, the Users list and the emails RenewCMS sends. Clear it to go back to your username.
- Send yourself a password reset link from the Profile page.
- The account chip now opens a menu with Profile and Log out, and keeps the System, Light and Dark theme choice.
## Improvements and fixes
- Accepting an invite is atomic: two simultaneous requests with the same link can only create one account.
- The Accept invite screen shows a retry option instead of a permanent spinner when the invite can't be loaded.
- Invite email validation is now the same in the browser and on the server.
- The mobile account sheet reports its open state correctly and returns focus to the account chip when it closes.
- A failed password reset email is now logged on the server. The response is unchanged.
## API
- `PATCH /v1/user/me` sets the display name.
- `GET /v1/auth/me` and `POST /v1/auth/verify` now return `display_name`.
- `GET /v1/user/` lists users and invites.
- `POST /v1/user/invite` sends an invite and is rate limited.
- `GET /v1/auth/invite` and `POST /v1/auth/invite/accept` power the Accept invite screen.
## Under the hood
- Deleting a user now goes through the persistence model.
## Upgrading
- Download the binary for your platform, replace the old one and restart. Your `.env` and SQLite file stay as they are.
- The database migrates itself on startup. It adds a `display_name` column to `users` and a new `invites` table. Existing data is untouched. Back up your SQLite file first as a precaution.
- Invitation emails need working SMTP settings, like the verification and reset emails already do. No new environment variables.
## Known limitations
- Users and invites can't be removed, revoked or resent yet, and there are no roles: everybody is an equal admin.
- Invited addresses that already have an account are rejected. An expired invite can be replaced by sending a new one.
+42
View File
@@ -0,0 +1,42 @@
RenewCMS now knows who owns the workspace. The owner manages invites, including cancelling and renewing them, while every admin keeps the same access to content. A new Settings page shows which build is running.
## New
**Owner and admin roles**
- The first registered account is the owner. Everyone who joins through an invite is an admin.
- Only the owner can send, cancel or renew invites. Admins keep the same access to articles, images, the Users list, their Profile and Settings.
- There is exactly one owner. Roles can't be changed or transferred yet.
- Existing installs are migrated automatically: the oldest account becomes the owner and every other account an admin.
**Invite management**
- Pending invites get a Cancel invite action on the Users page. The invite link stops working.
- Expired invites get a Renew invite action. It sends a new email with a new personal link valid for 3 days, and the old link stays dead.
**Users list**
- The Users table and the mobile card list now show Email, Display name (a dash when empty), Role, Invite status and Created.
- A new role badge tells the owner and admins apart.
**Settings page**
- A new Settings page at `/settings` sits after Integration in the sidebar and the mobile drawer. It shows the version of the running build.
## Improvements and fixes
- The desktop account menu's icons, labels and check mark are now centred in their 32 px rows.
- The account menu follows the redesigned board: System, Light and Dark stay in both the menu and the mobile sheet.
- The article editor's toolbar scrolls horizontally on mobile instead of overflowing.
- The editor's last-saved label now moves from minutes to hours and days instead of counting minutes only.
## API
- `DELETE /v1/user/invite/{id}` cancels a pending invite and returns 204.
- `POST /v1/user/invite/{id}/renew` returns 200 with a new code, sets `expires_at` to now plus 3 days and `created_at` to now, and resends the invitation email.
- Changed: `POST /v1/user/invite` is now owner-only, like the two endpoints above. Other users get 403 with "Only the owner can do this."
- `GET /v1/settings` (authenticated, verified users) returns the running build's version.
- Changed: user objects from `GET /v1/user/`, `GET /v1/auth/me` and `POST /v1/auth/verify` now include `role` (`owner` or `admin`).
## Upgrading
- Replace the binary and restart. Your `.env` and SQLite file stay as they are.
- The database migrates itself on startup. It adds a `role` column to `users` and fills it in: the account with the lowest id becomes the owner, every other account an admin. A database that already has roles is left unchanged. Back up your SQLite file first as a precaution.
- Behaviour change: admins who joined through a v2.3.0-beta invite can no longer send invites.
- No new environment variables.
## Known limitations
- No endpoint changes or transfers the owner role, and users can't be removed yet.
+160
View File
@@ -0,0 +1,160 @@
Feature: An invited person accepts their invitation and gets a verified account
As a person who received an invitation email
I want to open the link, see which address it was sent to, choose a username and password,
and land logged in
So that I get an account with exactly the same access as everyone else, while registration
stays closed to anyone who was not invited
Background:
Given GET /v1/auth/invite and POST /v1/auth/invite/accept are mounted in NewAuthRouter and are
public: no jwt cookie is required and an existing jwt cookie is ignored
And both are rate-limited per client IP with the auth rate limiter (AUTH_RATE_LIMIT_MAX_ATTEMPTS,
AUTH_RATE_LIMIT_WINDOW_SECONDS), counted independently of /login, /password-reset and
POST /v1/user/invite
And an invite is looked up by comparing the raw code against the stored hashed code with the
same hash.Hasher used to create it, and the raw code is never stored
And an invite is usable only when accepted_at is empty and expires_at is in the future
And a code that matches no invite, matches an accepted invite, or is missing or empty answers
404 with body apperr.InviteInvalidErrorMessage "This invite link doesn't work."
And a code that matches an unaccepted invite whose expires_at is in the past answers 410 with
body apperr.InviteExpiredErrorMessage "This invite has expired."
And the POST body has the validate tags code required, username required,min=3,max=20 and
password required,min=8, checked with validator.Validate.Struct before any lookup, and a
failure answers 400 with the validator's text; an unparseable body answers 400 with
apperr.BodyErrorMessage
And error responses are plain text from http.Error, success responses are JSON
And accepting creates a user with the invite's email (already lower case), the chosen username,
the hashed password, is_verified true, an empty verification code, and an empty display name
And the created user is an admin: same access to articles, the users list and Settings, but
cannot invite
And the jwt cookie is set exactly as registration sets it: HttpOnly, path "/", 24 hours, with
claims user_id and token_version, and Secure in production
Scenario: The invited email is read from a valid code
Given a pending invite for "lea.martin@renew.example" whose raw code is "3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42"
When the client sends GET /v1/auth/invite?c=3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42
Then the response status is 200
And the response body is a JSON object with exactly the key email, with value "lea.martin@renew.example"
And the response has Cache-Control "no-store"
And the invite is unchanged
Scenario Outline: A link that does not work is reported without saying why
Given a pending invite for "lea.martin@renew.example", an accepted invite for "sam@renew.example"
and an expired invite for "p.huber@gmail.com", each with its own raw code
When the client sends GET /v1/auth/invite<query>
Then the response status is <status>
And the response body is "<body>"
Examples:
| query | status | body |
| ?c=not-a-known-code | 404 | This invite link doesn't work. |
| ?c=<accepted invite code> | 404 | This invite link doesn't work. |
| ?c= | 404 | This invite link doesn't work. |
| | 404 | This invite link doesn't work. |
| ?c=<expired invite code> | 410 | This invite has expired. |
Scenario: Accepting creates a verified user, logs them in and closes the invite
Given a verified user "marta" and a pending invite for "Lea.Martin@Renew.example" created at
invitation time, with raw code "3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42"
When the client sends POST /v1/auth/invite/accept with body
{"code": "3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42", "username": "lea", "password": "limewash2026"}
Then the response status is 200
And the response body is a JSON object {"message": "Invite accepted! HTTPonly jwt cookie created"}
And a jwt cookie is set, and decoding it gives the new user's id and token_version
And the user repository holds a user "lea" with email "lea.martin@renew.example", is_verified
true, an empty verification_code and a stored password that is a hash, not "limewash2026"
And the invite now has accepted_at set and its status is "accepted"
And no email was sent
Scenario: The new account works like any other account
Given the invite from the previous scenario was accepted and the jwt cookie was kept
When the client sends GET /v1/auth/me and GET /v1/user/ with that cookie
Then both responses are 200
And the GET /v1/user/ list shows user "lea" with status "accepted" and no invite for
"lea.martin@renew.example"
Scenario: An accepted code cannot be used again
Given an invite that was just accepted by "lea"
When the client sends POST /v1/auth/invite/accept with the same code, username "lea2" and
password "limewash2026"
Then the response status is 404
And the response body is "This invite link doesn't work."
And no user "lea2" exists and no jwt cookie is set
When the client sends GET /v1/auth/invite with the same code
Then the response status is 404
Scenario Outline: A code that cannot be used creates nothing
Given <state>
When the client sends POST /v1/auth/invite/accept with a body using <code> and username "lea" and password "limewash2026"
Then the response status is <status>
And the response body is "<body>"
And no user was created, no jwt cookie is set and no invite changed
Examples:
| state | code | status | body |
| no invite has that code | an unknown one | 404 | This invite link doesn't work. |
| an invite that expired an hour ago | its code | 410 | This invite has expired. |
Scenario: A taken username is refused and the invite stays usable
Given a verified user "marta" and a pending invite for "lea.martin@renew.example"
When the client sends POST /v1/auth/invite/accept with username "marta" and password "limewash2026"
Then the response status is 409
And the response body is "That username is taken. Try another."
And no jwt cookie is set and the invite is still pending
When the client resends with username "lea"
Then the response status is 200
Scenario: An address that got an account in the meantime is refused
Given a pending invite for "lea.martin@renew.example" and an unverified user "leam" with email "Lea.Martin@Renew.example"
When the client sends POST /v1/auth/invite/accept with username "lea" and password "limewash2026"
Then the response status is 409
And the response body is exactly apperr.EmailHasAccountErrorMessage
And no user "lea" was created, no jwt cookie is set and the invite is still pending
Scenario Outline: An invalid body is rejected before the code is looked up
Given a pending invite with a known code
When the client sends POST /v1/auth/invite/accept with body <body>
Then the response status is 400
And no user was created and the invite is still pending
Examples:
| body |
| {"code": "<code>", "username": "le", "password": "limewash2026"} |
| {"code": "<code>", "username": "abcdefghijklmnopqrstu", "password": "limewash2026"} |
| {"code": "<code>", "username": "lea", "password": "lime"} |
| {"code": "<code>", "password": "limewash2026"} |
| {"username": "lea", "password": "limewash2026"} |
| not json |
Scenario: An existing jwt cookie is ignored and replaced
Given a valid jwt cookie for verified user "marta" and a pending invite for "lea.martin@renew.example"
When the client sends POST /v1/auth/invite/accept with that cookie and username "lea", password "limewash2026"
Then the response status is 200
And the Set-Cookie jwt carries the new user's id, not marta's
Scenario: A failure while accepting rolls back and leaves the invite pending and no user behind
Given a pending invite and the accept operation of the invite repository set to fail
When the client sends POST /v1/auth/invite/accept with username "lea" and password "limewash2026"
Then the response status is 500
And the user insert and the invite update are rolled back together
And no user "lea" exists, no jwt cookie is set and the invite is still pending
Scenario: The accept endpoints are rate-limited
Given AUTH_RATE_LIMIT_MAX_ATTEMPTS is 2 for a window covering the whole test
When the client at IP "203.0.113.30" sends 2 requests to POST /v1/auth/invite/accept and then a 3rd
Then the 3rd response is 429 with body apperr.TooManyRequestsErrorMessage and a Retry-After header
And GET /v1/auth/registration from the same client is not rejected with 429
Scenario: Registration stays closed for everyone else
Given a verified user and an accepted invite
When the client sends POST /v1/auth/register with username "sam", password "hunter2example12",
email "sam@renew.example"
Then the response status is 403
And the response body is exactly apperr.RegistrationClosedErrorMessage
And GET /v1/auth/registration still reports {"open": false}
Scenario: The invite response never leaks the code or other invite data
Given a pending invite
When the client sends GET /v1/auth/invite with its code
Then the body contains no key named code, hashed_code, invited_by, expires_at, id or accepted_at
+38
View File
@@ -0,0 +1,38 @@
# QA procedure: accept invitation (API)
Package `test` (black-box). Reuse `mockUserRepo`, `stubHasher`, `mockMailRepo`, `mockInviteRepo` (extend it with an accept method and a `failSwitch` entry for it; type names stay unique in the package).
## Setup shared by every case
1. `validator.InitValidator()` once.
2. Use cases: the accept use case (constructor takes only domain interfaces: user repo, invite repo, hasher; final names are the coder's), a get-invite use case for GET, plus `CreateUser`, `GetUser`, `ListUsersAndInvites` for the regression cases.
3. Handler built with `NewHandler(...)` over the use cases, mounted on a fresh `chi.NewRouter()` mirroring `NewAuthRouter`: `GET /invite` and `POST /invite/accept` inside a group with `TrustedProxyRealIP(nil)` + `NewRateLimiter(...)`; `/register`, `/registration` and (with `jwtauth.Verifier`, `Authenticator`, `RequireCurrentToken`) `/me` for regression. `jwtauth.New("HS256", []byte("test-secret"), nil)`. `httptest` only.
4. Seed invites via `mockInviteRepo` with `HashedCode == "hashed:"+rawCode` (stubHasher); times relative to `time.Now()`, 5 s tolerance.
## GET /v1/auth/invite
5. Valid code -> 200; decode `map[string]json.RawMessage`: keys exactly `email`; value the stored lower-case email; `Cache-Control: no-store`; invite unchanged. Raw body contains none of `code`, `hashed_code`, `invited_by`, `expires_at`, `id`, `accepted_at`.
6. Table: unknown code, accepted invite code, `?c=`, no query -> 404 with body exactly `apperr.InviteInvalidErrorMessage`; expired code -> 410 with `apperr.InviteExpiredErrorMessage`.
## POST /v1/auth/invite/accept
7. Happy path: body `{code, username:"lea", password:"limewash2026"}` -> 200, `{"message":…}`. `Set-Cookie` `jwt` HttpOnly, Path "/", decode via `jwtauth` to get `user_id` and `token_version` of the created user. `userRepo`: user "lea", `Email=="lea.martin@renew.example"`, `IsVerified`, empty `VerificationCode`, password `"hashed:limewash2026"`. Invite `AcceptedAt` not nil. `SentEmails` empty.
8. Follow-up with the cookie: `GET /me` -> 200; list use case shows user "lea" and no invite for the address.
9. Repeat POST with the same code -> 404 `InviteInvalid`, no user "lea2", no `Set-Cookie`; GET same code -> 404.
10. Table for 404 (unknown code) and 410 (expired an hour ago): exact bodies, no user, no cookie, invites unchanged.
11. Username "marta" taken -> 409, body `apperr.UsernameTakenErrorMessage` ("That username is taken. Try another."), no cookie, invite still pending; retry with "lea" -> 200.
12. Unverified user with email `Lea.Martin@Renew.example` present -> 409, body `apperr.EmailHasAccountErrorMessage`, no user created, invite pending, no cookie.
13. 400 table (username 2 chars, 21 chars, password 4 chars, no username, no code, `not json`): status 400, user repo and invite unchanged. Code lookup is not reached (assert the invite repo saw no accept call).
14. Cookie of verified user 7 sent with a valid accept -> 200 and the new cookie's `user_id` is the new user's.
15. Invite repo `AcceptWithUser` set to fail (`failSwitch`) -> 500, no user "lea" remains (the failed accept created none, and the use case never calls user repo `Delete`), invite pending, no cookie. The real rollback is covered against SQLite in `test/accept_invitation_atomic_test.go`.
16. Rate limit: limiter of 2 per minute, `RemoteAddr` `203.0.113.30:1234`, three POSTs -> third is 429 with body `apperr.TooManyRequestsErrorMessage` and `Retry-After`; `GET /registration` afterwards is not 429.
## Regression
17. Verified user present: `POST /register` -> 403 body `apperr.RegistrationClosedErrorMessage`, no user created; `GET /registration` -> `{"open":false}` after an invite was accepted. Empty user repo -> `POST /register` still 200 with a `verification` mail.
## Use case level (no HTTP)
18. Accept use case: unknown or empty code -> `errors.Is(err, invite.ErrInviteNotFound)`; expired -> an expired sentinel; taken username -> a username-taken sentinel; email owned -> `invite.ErrEmailHasAccount` (sentinel names are the coder's). Domain sentinels asserted with `errors.Is`.
## Open questions (no design state, not invented)
- GET /v1/auth/invite failing on load with a 500 or a network error: the design has no state for it.
- 429 on POST /v1/auth/invite/accept: the SPA shows the design's server-error alert ("Couldn't create the account").
## Manual verification
- Fresh SQLite file: invite acceptance persists across restart, `accepted_at` stored, unique username constraint holds; send a real invitation and open its link end to end (real SMTP, real embedded SPA).
+105
View File
@@ -0,0 +1,105 @@
Feature: Accept invite screen
As a person who opened the link in the invitation email
I want /invite/accept?c=CODE to show me the invited address and let me choose a username and
password
So that I finish setting up my account and arrive logged in
Background:
Given /invite/accept is a public route (meta.auth "public") rendered as AcceptInvitePage inside
AuthShell, per docs/design/routes.md
And on mount AcceptInvitePage reads the "c" query parameter once: if it is absent or empty no
request is made and the "Invalid or used link (404)" state renders
And otherwise it calls GET /v1/auth/invite?c=CODE and shows "Checking the link" until it resolves
And the Username and Password rules are Register's, including PasswordStrengthHint, with no
confirm field; validation runs on blur and on submit and nothing is sent when it fails
And a submit that passes calls POST /v1/auth/invite/accept with { code: c, username, password }
And a logged-in visitor sees the same screen: the route stays public and nothing redirects
And the board is docs/design/source/RenewCMS Screens Auth.dc.html, group "Accept invite"; the
board frame decides layout and sample data (lea.martin@renew.example, "lea", "limewash2026",
"marta")
Scenario: Checking the link
When the user opens /invite/accept?c=abc123 and GET /v1/auth/invite has not resolved
Then a full-card spinner reads "Checking your invite…"
Scenario: Default
Given GET /v1/auth/invite?c=abc123 resolves 200 with {"email": "lea.martin@renew.example"}
Then the heading is "Accept your invite"
And the description is "Choose a username and password to finish setting up your account."
And the Email field has placeholder "you@example.com", shows "lea.martin@renew.example", is
read-only, with help "From your invitation."
And the Username field has placeholder "e.g. lea", counter "0 / 20" and help "Letters and numbers,
3 to 20 characters. You'll use it to log in."
And the Password field is a password input with show/hide and checklist "At least 8 characters" unmet
And the submit button reads "Accept invite"
And the footer reads "Already have an account?" with a "Log in" link to /login
Scenario: Validation errors
Given the form is shown, Username is "ma" and Password is "lime"
When the user blurs both fields and submits
Then POST /v1/auth/invite/accept is never called
And the Username shows counter "2 / 20" in error and the error "Use 3 to 20 characters."
And the checklist item "At least 8 characters" is in its error state
Scenario: Filled, valid
Given Username is "lea" and Password is "limewash2026" with the password shown
Then the counter reads "3 / 20", the checklist item "At least 8 characters" is met and no error shows
Scenario: Submitting
When the user submits valid values and POST /v1/auth/invite/accept has not resolved
Then the fields and button are disabled
And the submit button reads "Creating account…" and is loading
Scenario: Username taken (409)
When POST /v1/auth/invite/accept resolves 409 with body "That username is taken. Try another."
Then the Username keeps "marta", shows counter "5 / 20", is focused and shows the error
"That username is taken. Try another."
And the Password keeps its value, the form re-enables and the button reads "Accept invite"
Scenario Outline: The link does not work
When <trigger>
Then no form is shown
And a ResultPanel (tone error, icon i-lucide-link-2-off) reads "This invite link doesn't work"
with text "It may be incomplete, or it may already have been used. If you already set up your
account, log in instead." and note "Open the link from your email again, or copy the full
address into your browser."
And its only action is a primary "Go to log in" that navigates to /login
Examples:
| trigger |
| the user opens /invite/accept with no c parameter (no request is made) |
| GET /v1/auth/invite?c=abc123 resolves 404 |
| the submit resolves 404, replacing the form |
| the submit resolves 409 with apperr.EmailHasAccountErrorMessage |
Scenario Outline: Expired link (410)
When <trigger>
Then no form is shown
And a ResultPanel (tone error, icon i-lucide-clock) reads "This invite has expired" with text
"Invites work once, for 3 days. Ask the person who invited you to send a new one."
And its only action is a secondary "Go to log in" that navigates to /login
Examples:
| trigger |
| GET /v1/auth/invite?c=abc123 resolves 410 |
| the submit resolves 410, replacing the form |
Scenario Outline: Server error
When the submit <failure>
Then an error Alert (icon i-lucide-circle-x) reads "Couldn't create the account" with "Something
went wrong on the server. Try again in a moment." above the heading
And the form is still shown with Email, Username "lea" and Password "limewash2026" kept, re-enabled
Examples:
| failure |
| resolves 500 |
| resolves 429 |
| never reaches the server |
Scenario: Success
When POST /v1/auth/invite/accept resolves 200 with the jwt cookie
Then a ResultPanel (tone success, icon i-lucide-circle-check) reads "Your account is ready" with
text "Taking you to your dashboard…"
And a Toast (icon i-lucide-circle-check) reads "Welcome to RenewCMS" with "You're logged in as lea."
And after 800 ms the app navigates to /home with no verification step
+26
View File
@@ -0,0 +1,26 @@
# QA: Accept invite screen
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi` for GET `/v1/auth/invite` and POST `/v1/auth/invite/accept` per case; mount AcceptInvitePage inside AuthShell with a test router at `/invite/accept?c=abc123`. Use fake timers for the 800 ms redirect only; never freeze the date.
1. Checking the link: GET unresolved -> "Checking your invite…" spinner.
2. Default: GET 200 `{email:"lea.martin@renew.example"}` -> heading, description, read-only Email with help, Username "0 / 20" and its help, Password checklist unmet, button "Accept invite", footer "Log in" -> /login.
3. Validation errors: Username "ma", Password "lime", blur + submit -> no POST, "Use 3 to 20 characters.", counter "2 / 20" error, checklist error.
4. Filled, valid: "lea" / "limewash2026" shown -> "3 / 20", checklist met.
5. Submitting: POST unresolved -> fields disabled, "Creating account…" loading.
6. Username taken: POST 409 body "That username is taken. Try another." -> value "marta" kept, "5 / 20", focus on Username, error copy, password kept, form re-enabled.
7. Link does not work (table): no `c` (no request at all), GET 404, POST 404, POST 409 with `This address already has an account.` -> ResultPanel link-2-off with the title, text, note and one primary "Go to log in"; click navigates to /login.
8. Expired (table): GET 410, POST 410 -> ResultPanel clock, title, text, one secondary "Go to log in".
9. Server error (table): POST 500, POST 429, rejected fetch -> Alert "Couldn't create the account" + description, form kept.
10. Success: POST 200 -> ResultPanel "Your account is ready", Toast "Welcome to RenewCMS" / "You're logged in as lea."; advance 800 ms -> router path is /home.
11. Logged-in visitor: session store holds a verified user; mounting shows the Default state, no redirect.
## Open questions (no design state, not invented)
- GET /v1/auth/invite failing on load with a 500 or a network error: the design has no state for it.
## Visual (`task visual:check -- accept-invite`, desktop and mobile, light and dark; hard gate 10 %)
Sample data from the board frame: email `lea.martin@renew.example`; username `lea` (taken state: `marta`); password `limewash2026`; validation state username `ma`, password `lime`. States: Checking the link, Default, Validation errors, Filled valid, Submitting, Username taken (409), Invalid or used link (404), Expired link (410), Server error, Success. `skip: clock-sensitive`: none (expiry is driven by the 410 status, not the clock). Layout placement comes from the board frame markup, not from components.md prose.
## Manual checks (not covered by screenshots)
- Keyboard: Tab order Username -> Password -> show/hide -> Accept invite -> Log in; Username is focused after a 409; the ResultPanel title takes focus on 404/410.
- Password show/hide and hover states; the 800 ms hand-off; the Toast disappearing.
- Real e2e: open the emailed link against `task dev`.
+21 -18
View File
@@ -17,15 +17,17 @@ Feature: DashboardShell wordmark, sidebar collapse and the UserMenu
AuthShell uses) followed by the "RenewCMS" wordmark text, not the plain
<span class="font-semibold">RenewCMS</span> the shell renders today
And the sidebar's #default slot is a UNavigationMenu orientation="vertical" :collapsed bound
to the sidebar's own collapsed state, with items Home, Articles and Integration
to the sidebar's own collapsed state, with items Home, Articles, Users, Integration and Settings, in that order
And the sidebar's #footer slot renders a UserMenu component, not the plain
<span>Log out</span> text the shell renders today
And UserMenu is a UDropdownMenu :content="{ side: 'top', align: 'start' }" anchored to a
ghost UButton block containing a UAvatar and the session's username
And the UAvatar's initials are the first two characters of the username, upper-cased (for
example "marta" gives "MA"), and the avatar is aria-hidden because the username is shown
next to it
And UserMenu's dropdown groups, top to bottom, are: an account label (the username); a
And UserMenu is the account menu specified in features/profile_page.feature, anchored to a
ghost UButton block containing a UAvatar and the session's name (the display name when not
empty, else the username)
And the UAvatar's initials follow features/profile_page.feature (the first letters of the
first two words of a display name, the first two characters of a single word or of a
username, upper-cased; for example "marta" gives "MA"), and the avatar is aria-hidden
because the name is shown next to it
And UserMenu's groups, top to bottom, are: a header (the name and the email); Profile; a
checkbox group of System, Light and Dark bound to useColorMode().preference, with the
current preference's item checked; then Log out, in its own trailing group
And Log out calls POST /v1/auth/logout inside a try/finally with a loading flag (no catch),
@@ -53,15 +55,16 @@ Feature: DashboardShell wordmark, sidebar collapse and the UserMenu
Then the sidebar returns to its :default-size="14" expanded width
And aria-expanded reflects the expanded state
Scenario: UserMenu's dropdown lists the account label, color-mode checkboxes, then Log out
Given the session's username is "marta"
Scenario: UserMenu lists the header, Profile, color-mode checkboxes, then Log out
Given the session's username is "marta" and its email is "marta@renew.example"
When the user activates the UserMenu trigger in the sidebar footer
Then the dropdown opens with a UAvatar showing initials "MA" and the trigger's own username
text "marta"
And the first group is the account label showing "marta"
And the second group is a checkbox group with items System, Light and Dark, and exactly the
Then the menu opens with a UAvatar showing initials "MA" and the trigger's own name text
"marta"
And the first group is the header showing "marta" and "marta@renew.example"
And the next item is "Profile"
And the following group is a checkbox group with items System, Light and Dark, and exactly the
item matching the current useColorMode().preference is checked
And the third and final group contains only "Log out", separated from the color-mode group
And the final group contains only "Log out", separated from the color-mode group
Scenario Outline: Selecting a color-mode item updates the preference and its checked state
Given the user has opened the UserMenu dropdown
@@ -91,11 +94,11 @@ Feature: DashboardShell wordmark, sidebar collapse and the UserMenu
And the header keeps an accessible name for the brand mark (an aria-label or sr-only text
reading "RenewCMS" on the logo or its wrapper), so collapsing the rail is not a pure a11y
regression
And the UserMenu trigger in the sidebar footer still shows the UAvatar, but the username text
And the UserMenu trigger in the sidebar footer still shows the UAvatar, but the name text
next to it is hidden
And the UserMenu trigger keeps an accessible name that includes the username (an aria-label
And the UserMenu trigger keeps an accessible name that includes the name (an aria-label
such as "marta — account menu", or a tooltip plus aria-label), matching the same
tooltip/aria-label spirit the collapsed rail's UNavigationMenu items already use per
docs/design/components.md's DashboardShell a11y note
And activating the collapsed UserMenu trigger still opens the same dropdown, with the same
account label, color-mode checkbox group and Log out item as the expanded state
And activating the collapsed UserMenu trigger still opens the same menu, with the same
header, Profile, color-mode checkbox group and Log out item as the expanded state
+131
View File
@@ -0,0 +1,131 @@
Feature: Crop and resize step in the editor's image uploader
As a verified RenewCMS owner adding an image to an article
I want to crop and resize a JPEG, PNG or WEBP before it uploads
So that I control the framing and file size of images in my articles, without needing an
external editor
Background:
Given ImageUploader inserts a crop-and-resize step between the idle file picker and the
upload, for any JPEG, PNG or WEBP that already passed the browser validation described in
features/editor_image_upload.feature; that feature's idle, dragging-over, rejected,
uploading, inserted and failed states and its POST /v1/article/{articleId}/image contract
are unchanged and out of scope here
And an SVG file skips this step entirely and uploads immediately, as before
And opening the step retitles the modal from "Add an image" to "Crop and resize", with the
description "{filename} · {size}" (e.g. "north-wall.jpg · 3.9 MB")
And the stage shows the chosen image at its natural pixel dimensions with a crop frame that
starts as the whole image: a rule-of-thirds grid (lines at 33.3 %/66.6 %), four 12×12 px
corner handles, and a mono pixel-size label in a dark pill at the frame's bottom-left
corner, tracking the frame's current size
And the frame is reachable by Tab (tabindex="0"), aria-label "Crop area. Arrow keys move it,
Shift and arrow keys resize it."; dragging the frame moves it, dragging a handle resizes
it, arrow keys nudge it by 1 px, and Shift+arrow keys resize it by 1 px
And above the frame, "Aspect ratio" is a radiogroup of five pills — Original, Free, 16:9,
4:3, 1:1 — next to "Rotate" and "Reset" actions; "Width" is a second radiogroup — Original,
1600 px (default), 1200 px, 800 px
And a mono line below reads "Uploads as {width} × {height} px · about {size}" (KB under
1 MB, MB at or above it), recomputed whenever the ratio, width, frame rect or rotation
changes
And the output width is min(the chosen width preset, the crop frame's own pixel width) —
never upscaled — and the output height keeps the crop frame's own aspect ratio; when the
crop is narrower than the chosen width, an info row reads "The crop is {crop width} px
wide, so it's uploaded at that size. Enlarging it would make it blurry."
And the footer offers "Choose another file" (discards this step and returns to the idle file
picker with no adjustments carried over) and "Upload image" (uploads the cropped, resized
file through the unchanged POST /v1/article/{articleId}/image flow)
And "Rotate" turns the image 90° clockwise each activation, cycling 0°→90°→180°→270°→0°, and
width presets apply to the post-rotation image
And "Reset" returns the ratio to Original, the width to 1600 px, the crop frame to the whole
unrotated image, and the rotation to 0°, without closing the modal
Scenario: A raster file opens the crop-and-resize step instead of uploading immediately
Given ImageUploader is open in the idle state for article 12
When the user chooses a file named "north-wall.jpg", content type "image/jpeg", size 3.9 MB,
natural dimensions 4032 × 3024 px
Then no request is sent to POST /v1/article/12/image
And the modal retitles to "Crop and resize" with the description "north-wall.jpg · 3.9 MB"
And the crop frame starts as the whole image, ratio "Original" is selected, and width
"1600 px" is selected
And the mono line reads "Uploads as 1600 × 1200 px · about 420 KB"
And the footer reads "Choose another file" and "Upload image"
Scenario: An SVG skips the crop step and uploads immediately
Given ImageUploader is open in the idle state for article 12
When the user chooses a file named "diagram.svg", content type "image/svg+xml", size 40 KB
Then POST /v1/article/12/image is sent immediately with that file
And the crop-and-resize step is never shown
Scenario Outline: Choosing an aspect ratio locks the frame to it
Given the crop-and-resize step is open for "north-wall.jpg" (4032 × 3024 px), ratio
"Original", width "1600 px"
When the user selects ratio "<ratio>"
Then the crop frame becomes <crop_width> × <crop_height> px, centered on the image
And dragging or resizing the frame afterwards keeps that aspect ratio
And the mono line reads "Uploads as <out_width> × <out_height> px · about {size}"
Examples:
| ratio | crop_width | crop_height | out_width | out_height |
| 16:9 | 4032 | 2268 | 1600 | 900 |
| 4:3 | 4032 | 3024 | 1600 | 1200 |
| 1:1 | 3024 | 3024 | 1600 | 1600 |
Scenario: Choosing a narrower width preset recomputes the output without upscaling
Given the crop-and-resize step is open for "north-wall.jpg", ratio "Original", width
"1600 px"
When the user selects width "800 px"
Then the mono line reads "Uploads as 800 × 600 px · about {size}", a smaller estimate than
before
Scenario: A crop narrower than the chosen width is uploaded at its own size, not upscaled
Given the crop-and-resize step is open for "north-wall.jpg", ratio "1:1", width "1600 px"
When the user resizes the crop frame down to 640 × 640 px
Then the mono line reads "Uploads as 640 × 640 px · about {size}"
And an info row reads "The crop is 640 px wide, so it's uploaded at that size. Enlarging it
would make it blurry."
Scenario: Free ratio removes the aspect-ratio constraint
Given the crop-and-resize step is open for "north-wall.jpg", ratio "Original"
When the user selects ratio "Free"
Then the crop frame can be dragged or resized to any width and height independently, no
longer snapping to a fixed ratio
Scenario: Arrow keys move the crop frame and Shift+arrow keys resize it
Given the crop-and-resize step is open for "north-wall.jpg" with the crop frame focused
When the user presses ArrowRight
Then the frame moves 1 px right and the mono line's size is unchanged
When the user presses Shift+ArrowRight
Then the frame's width grows by 1 px and the mono line updates to the new output size
Scenario: Rotate cycles the image in 90° steps and Reset returns to the opened defaults
Given the crop-and-resize step is open for "north-wall.jpg" at ratio "16:9", width "800 px"
When the user activates "Rotate"
Then the image and crop frame rotate 90° clockwise
When the user activates "Reset"
Then ratio returns to "Original", width returns to "1600 px", the frame returns to the
whole, unrotated image, and the mono line reads "Uploads as 1600 × 1200 px · about 420 KB"
Scenario: "Choose another file" returns to the file picker without uploading
Given the crop-and-resize step is open for "north-wall.jpg"
When the user activates "Choose another file"
Then no request is sent to POST /v1/article/12/image
And the idle state is shown again, with the file picker available
Scenario: A newly chosen file opens a fresh crop step, not the previous file's adjustments
Given the user returned to idle via "Choose another file" from a crop step that had ratio
"16:9" and width "800 px"
When the user chooses a new file named "sunset.jpg", content type "image/jpeg", size 2.1 MB,
natural dimensions 3000 × 2000 px
Then the crop-and-resize step reopens with ratio "Original", width "1600 px", and the frame
as the whole new image
Scenario: "Upload image" uploads the cropped, resized file, not the original
Given the crop-and-resize step is open for "north-wall.jpg" with ratio "Original", width
"1600 px" and the mono line "Uploads as 1600 × 1200 px · about 420 KB"
When the user activates "Upload image"
Then POST /v1/article/12/image is sent with a single file under the field name "file" whose
pixel dimensions are 1600 × 1200 and whose size is about 420 KB, not the original
4032 × 3024, 3.9 MB file
And the uploading state shows "Uploading 0.0 of 420 KB"
When the upload reports 180 KB sent of 420 KB
Then the uploading state shows "north-wall.jpg 43%" and "Uploading 180 of 420 KB"
+86
View File
@@ -0,0 +1,86 @@
# QA: Crop and resize step in the editor's image uploader
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mount EditorPage inside DashboardShell at `/article/12/edit` with the editor_core.qa.md fixture
article (id 12, "How we price a bathroom renovation", is_online false), GET already resolved
200. Reuse editor_image_upload.qa.md's fake-XHR setup for the upload itself. Stub the chosen
file's decoded natural size (e.g. mock `Image`/`createImageBitmap` or whatever the component
uses to read `naturalWidth`/`naturalHeight`) so tests control it deterministically, and stub the
crop/resize step's own output producer (whatever function turns the frame rect + width preset
into a Blob) as a spy, asserting it is called with the frame's rect in natural-image pixels and
the resolved output width/height, and stubbing its returned Blob's size — without asserting how
it renders internally (canvas/OffscreenCanvas is a coder implementation detail).
1. **A raster file opens "Crop and resize" instead of uploading** — choose `north-wall.jpg`
(image/jpeg, 3.9 MB, natural 4032×3024); assert no XHR is created; assert the modal title is
"Crop and resize", description "north-wall.jpg · 3.9 MB", ratio "Original" and width
"1600 px" selected, mono line "Uploads as 1600 × 1200 px · about 420 KB", footer "Choose
another file" / "Upload image".
2. **An SVG bypasses the step** — choose `diagram.svg` (image/svg+xml, 40 KB); assert an XHR to
`/v1/article/12/image` is created immediately and the crop step never renders.
3. **Ratio presets lock the frame, Examples-driven (16:9 / 4:3 / 1:1)** — from the opened step,
select each ratio pill; assert the frame's reported rect and the mono line's output size match
the feature's Examples table.
4. **Width preset recomputes the output** — select width "800 px"; assert the mono line reads
"Uploads as 800 × 600 px" (assert dimensions exactly; assert only that the size figure changed
to a smaller value, not a specific number).
5. **A crop narrower than the width shows the info row and keeps its own size** — resize the
frame (via its resize API/spy) to 640×640 with ratio "1:1", width "1600 px"; assert the mono
line reads "Uploads as 640 × 640 px · about {size}" and the info row reads exactly "The crop
is 640 px wide, so it's uploaded at that size. Enlarging it would make it blurry."
6. **Free ratio removes the constraint** — select ratio "Free"; assert a subsequent resize call
with independent width/height is accepted without being coerced back to a ratio.
7. **Arrow and Shift+Arrow keys move/resize** — focus the frame; fire `ArrowRight`; assert the
frame's x increases by 1 px and the mono line's size is unchanged; fire `Shift+ArrowRight`;
assert the frame's width increases by 1 px and the mono line updates.
8. **Rotate cycles 90° and Reset restores defaults** — activate "Rotate"; assert the reported
rotation is 90°; activate "Reset"; assert ratio "Original", width "1600 px", the frame back to
the whole unrotated image, and the mono line "Uploads as 1600 × 1200 px · about 420 KB".
9. **"Choose another file" discards the step** — activate it; assert no XHR was created and the
idle state renders.
10. **A newly chosen file reopens at defaults** — from idle after "Choose another file" out of a
16:9/800px step, choose `sunset.jpg` (image/jpeg, 2.1 MB, natural 3000×2000); assert the new
crop step opens with ratio "Original", width "1600 px", frame as the whole new image (not the
previous file's ratio/width).
11. **"Upload image" sends the cropped/resized file** — from the default 1600×1200/420 KB step,
activate "Upload image"; assert the XHR is created with a file whose declared size is 420 KB
(not 3.9 MB); assert the uploading state shows "Uploading 0.0 of 420 KB"; fire an
`upload.progress` with `loaded: 180 * 1024, total: 420 * 1024`; assert "north-wall.jpg 43%"
and "Uploading 180 of 420 KB".
## Visual (manual verification via `task visual:check -- editor` — desktop and mobile, light and
dark)
Reference: `docs/design/screens/editor.md` states "Upload: crop and resize", "Upload: crop to a
ratio", "Upload: crop narrower than the width", and the updated "Upload: in progress"; board
`docs/design/source/RenewCMS Screens Back-office.dc.html`, group "Editor". Add each state's mock
setup to `web/visual/states.ts`, reusing editor_core.qa.md's fixture article (id 12, "How we
price a bathroom renovation", draft) and the sample file "north-wall.jpg · 3.9 MB".
- [ ] Upload: crop and resize — modal "Crop and resize" / "north-wall.jpg · 3.9 MB", ratio
"Original", width "1600 px", cancel "Choose another file", confirm "Upload image".
- [ ] Upload: crop to a ratio — same modal, ratio "16:9" selected, frame locked to that ratio.
- [ ] Upload: crop narrower than the width — ratio "1:1", width "1600 px", frame resized to
640×640, info row "The crop is 640 px wide, so it's uploaded at that size. Enlarging it
would make it blurry."
- [ ] Upload: in progress (updated) — modal "Add an image", uploading "north-wall.jpg 43%" /
"Uploading 180 of 420 KB", cancel "Cancel upload".
- [ ] Mobile (all of the above at 390×844): same modal layout constraints as other editor modals.
- [ ] Keyboard/focus: the crop frame is reachable by Tab; its `aria-label` is "Crop area. Arrow
keys move it, Shift and arrow keys resize it."; Arrow/Shift+Arrow move and resize it without
moving focus elsewhere; the aspect-ratio and width radiogroups follow standard roving-tabindex
radiogroup keyboard behavior (arrow keys between pills, one tab stop per group); "Rotate" and
"Reset" are reachable and named by their visible text.
- [ ] Motion: no auto-close or timed transition in this step; frame drag/resize follows pointer
with no easing delay (not part of the 10 % capture budget, spot-checked only).
## Manual verification
- **Real image decoding and resizing** — Vitest stubs `naturalWidth`/`naturalHeight` and the
output producer; confirm real JPEG/PNG/WEBP files of varying orientations and EXIF rotation
crop, rotate and resize correctly against `task dev` with a live server, since jsdom has no
real canvas/image pipeline.
- **Real POST of the resized file** — confirm the actual uploaded bytes decode to the expected
pixel dimensions server-side, complementing `features/upload_article_image.feature`'s
httptest coverage of the handler in isolation.
+148
View File
@@ -0,0 +1,148 @@
Feature: Removing an inline image from the editor
As a verified RenewCMS owner writing an article
I want to remove an image I've already inserted into the article body,
either through an explicit delete button or by pressing Backspace/Delete
on the selected image, directly from the editor
So that a mistaken or unwanted image doesn't have to stay in the article
forever, and removing it behaves like every other destructive action in
RenewCMS: it asks for confirmation first, however the user starts it
Background:
Given docs/design/ has no board or state for removing an inline image;
this feature was added at the user's explicit request ahead of design
coverage, reusing the editor's existing visual language rather than
inventing new components: the trash icon and error color already used
by the article "Delete" button, and the ConfirmDialog component
already used by "Delete this article?" (docs/design/screens/editor.md's
"Delete: confirm" state)
And this slice changes ArticleEditor's exposed insertImage(src, alt) to
insertImage(src, alt, imageId), stamping the inserted <img> node with
the image's numeric id as a data-image-id attribute, persisted in the
saved article body HTML; EditorView passes the id it now receives from
a successful upload (features/remove_article_image.feature's change to
POST .../image's 201 body) through to insertImage
And an image already present in an article's body from before this slice
has no data-image-id attribute and so shows no delete affordance and
is not intercepted by Backspace/Delete, until it is removed and
re-added
And selecting an image node that does carry a data-image-id attribute
shows a small delete button anchored to the image's top-right corner,
icon i-lucide-trash-2, color error, matching the article Delete
button's icon and color; deselecting the image (clicking elsewhere)
hides it
And there are two equivalent triggers for the same removal flow:
activating that delete button, and pressing Backspace or Delete while
the image node is selected (a Tiptap NodeSelection on the image).
Tiptap's native node deletion on Backspace/Delete is intercepted
before it reaches the document (e.g. via a keyboard-shortcut/keydown
handler registered on the Image node or at the editor level, checked
first while an image node is selected) so the key press never removes
the node directly; instead it triggers exactly the same flow as the
button
And either trigger emits ArticleEditor's new "request-remove-image"
event with the node's numeric image id; ArticleEditor does not call
the API or show any dialog itself, mirroring how "request-image"
already only opens ImageUploader from EditorView
And EditorView reacts to "request-remove-image" by opening the existing
ConfirmDialog component with title "Remove this image?", description
"This image will be removed from the article. This can't be undone.",
confirmLabel "Remove image", cancelLabel "Cancel", pendingLabel
"Removing…", tone "danger" — the same component and tone already used
for "Delete this article?"
And ConfirmDialog's action calls DELETE /v1/article/{articleId}/image/
{imageId} through useApi (not the raw XMLHttpRequest used for upload,
since there is no progress to observe)
And on success (204) the action removes the image node from
ArticleEditor's content via a new exposed removeImage(imageId) method,
which moves useArticleDraft's state to "dirty" the same way any other
body edit does; ConfirmDialog then closes and a toast appears: color
success, icon i-lucide-circle-check, title "Image removed",
description "Save to keep this change."
And on any failure (404 for either the article or the image, 500, or a
network failure) the action throws, so ConfirmDialog shows its own
inline error "Couldn't remove the image, so it's still there. Try
again in a moment." and stays open; the image node is not removed and
the draft's dirty state is unchanged
And a 401 is handled entirely by useApi's global handling
(features/api_client_global_error_handling.feature) and is out of
scope for new scenarios here
And once the confirm dialog is open, its cancel/confirm/failure
behaviour (covered below) is identical regardless of which trigger
opened it, so those scenarios are written once, against the button
trigger, and are not duplicated per trigger
Scenario: Selecting an inserted image reveals its delete button
Given the user is on /article/12/edit with an image in the body carrying
data-image-id "10"
When the user clicks that image
Then a delete button (trash icon, error color) appears at the image's
top-right corner
When the user clicks elsewhere in the editor
Then the delete button is no longer shown
Scenario Outline: Either trigger opens the confirm dialog and sends no request yet, without letting Tiptap delete the node itself
Given the image with data-image-id "10" is selected on /article/12/edit
When the user <triggers-removal>
Then a dialog titled "Remove this image?" opens, with description "This
image will be removed from the article. This can't be undone.",
cancel "Cancel" and confirm "Remove image"
And no request has been sent to DELETE /v1/article/12/image/10
And the image node is still present in the editor's content (Tiptap's
native node deletion did not run)
Examples:
| triggers-removal |
| activates the image's delete button |
| presses Backspace with the image node selected |
| presses Delete with the image node selected |
Scenario: Cancelling the confirm dialog changes nothing
Given the confirm dialog is open for image id 10 on /article/12/edit
When the user activates "Cancel"
Then the dialog closes
And no request has been sent to DELETE /v1/article/12/image/10
And the image is still present in the editor's content
And the draft's dirty state is unchanged
Scenario: Confirming removes the image, marks the draft dirty, and shows a success toast
Given the confirm dialog is open for image id 10 on /article/12/edit,
the draft in the Saved state
When the user activates "Remove image"
Then DELETE /v1/article/12/image/10 is sent
When that request resolves 204
Then the dialog closes
And the image is removed from the editor's content
And SaveStatus reads "Unsaved changes" and the Save button becomes
enabled
And a toast appears: color success, icon i-lucide-circle-check, title
"Image removed", description "Save to keep this change."
Scenario Outline: A failed removal keeps the image and shows the dialog's inline error
Given the confirm dialog is open for image id 10 on /article/12/edit
When the user activates "Remove image"
And DELETE /v1/article/12/image/10 <failure>
Then the dialog stays open, showing the inline error "Couldn't remove
the image, so it's still there. Try again in a moment."
And the image is still present in the editor's content
And the draft's dirty state is unchanged
Examples:
| failure |
| resolves with a 404 response |
| resolves with a 500 response |
| never reaches the server |
Scenario: Confirming a removal started by Backspace/Delete behaves exactly like confirming one started by the button
Given the confirm dialog is open for image id 10 on /article/12/edit,
opened by pressing Backspace with the image node selected, the draft
in the Saved state
When the user activates "Remove image"
Then DELETE /v1/article/12/image/10 is sent
When that request resolves 204
Then the dialog closes
And the image is removed from the editor's content
And SaveStatus reads "Unsaved changes" and the Save button becomes
enabled
And a toast appears: color success, icon i-lucide-circle-check, title
"Image removed", description "Save to keep this change."
+88
View File
@@ -0,0 +1,88 @@
# QA: Removing an inline image from the editor
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mount EditorPage inside DashboardShell at `/article/12/edit` with the
editor_core.qa.md fixture article (id 12, "How we price a bathroom
renovation", is_online false), GET already resolved 200, and a body
containing `<img src="/static/uploadedImages/before.png" data-image-id="10"
alt="">`. Mock `useApi`'s `request` for `DELETE /v1/article/12/image/10`
(fetch-based, not XHR — reuse whatever mock
`api_client_global_error_handling.qa.md` already sets up for `request`).
1. **Selecting the image reveals the delete button** — click the image
node; assert a delete button (trash icon, error color) renders anchored
to it; click elsewhere in the editor; assert the button is gone.
2. **Activating the delete button opens the confirm dialog** — select the
image, activate its delete button; assert a dialog titled "Remove this
image?", description "This image will be removed from the article. This
can't be undone.", cancel "Cancel", confirm "Remove image"; assert no
request was sent yet; assert the image node is still present (Tiptap's
native deletion did not run).
3. **Backspace on the selected image opens the same confirm dialog instead
of deleting the node** — select the image node (NodeSelection), fire a
`keydown` for `Backspace`; assert the same dialog as step 2 opens;
assert no request was sent yet; assert the image node is still present
in the editor's document (i.e. the keydown was intercepted before
Tiptap's default node-deletion ran, not just undone afterwards).
4. **Delete on the selected image opens the same confirm dialog instead of
deleting the node** — same as step 3 but firing `keydown` for `Delete`.
5. **Cancelling changes nothing** — from the open dialog (opened via the
button), click "Cancel"; assert the dialog closes, no request was sent,
the image node is still in the editor's content, and SaveStatus/dirty
state is unchanged.
6. **Confirming removes the image, marks dirty, and toasts (button
trigger)** — from the open dialog (Saved state), click "Remove image";
assert a DELETE request to `/v1/article/12/image/10` was made; resolve
it 204; assert the dialog closes, the image node is gone from the
editor's content, SaveStatus reads "Unsaved changes" and Save is
enabled, and a toast appears with color success, icon
`i-lucide-circle-check`, title "Image removed", description "Save to
keep this change."
7. **Confirming removes the image the same way when opened via
Backspace/Delete** — repeat step 6's assertions, but open the dialog via
the Backspace keydown from step 3 instead of the button; assert the
outcome (request, node removal, dirty state, toast) is identical.
8. **A failed removal keeps the image and shows the inline error,
Examples-driven** — for a 404 response, a 500 response, and a rejected/
network-failure request: from the open dialog (button trigger), click
"Remove image"; resolve/reject accordingly; assert the dialog stays open
showing the inline error "Couldn't remove the image, so it's still
there. Try again in a moment."; assert the image node is still present
and the draft's dirty state is unchanged.
## Visual
No `docs/design/` board or state exists for this trigger (see the feature's
Background). Per the user's explicit direction this slice ships the SPA
behaviour anyway, but `task visual:check -- editor` has nothing to compare
it against, so no visual capture is added for it — this is an intentional
gap, `skip: no-design-coverage` (distinct from `skip: clock-sensitive`), not
a QA oversight. If a board for this state is added to `docs/design/` later,
it needs its own follow-up slice to add the visual check.
- [ ] Keyboard/focus: once a delete button is shown, it is reachable by Tab
and activates on Enter/Space; pressing Backspace/Delete with the
image node selected but focus elsewhere in the page does not trigger
removal (only an actual Tiptap NodeSelection on the image should);
ConfirmDialog's existing focus trap and cancel-button-default-focus
behaviour (already covered by the article-delete flow) applies
unchanged regardless of which trigger opened it.
## Manual verification
- **Real DELETE round trip against a running server** — Vitest only mocks
`useApi`'s request; confirm a real removal (204/404/500) against
`task dev` with a live SQLite file and the real
`DELETE /v1/article/{id}/image/{imageId}` handler, since
`features/remove_article_image.feature`'s httptest suite covers the
handler in isolation but never through this SPA flow.
- **Real keyboard behaviour** — confirm in a real browser that selecting an
image (click) and pressing Backspace/Delete opens the confirm dialog
rather than deleting the node, including with an IME or on a platform
where Backspace/Delete semantics differ, since jsdom's `keydown`
simulation doesn't exercise Tiptap's real ProseMirror keymap precedence.
- **Design review of the delete-button/ConfirmDialog approach** — since
there is no board for this state, once a board is added, re-verify this
implementation still matches it (or update the implementation to match);
until then this is a best-effort, design-team-unreviewed UI.
+8 -7
View File
@@ -9,9 +9,10 @@ Feature: A logged-in user fetches their own public profile without triggering th
without being throttled like a login attempt
Background:
Given the existing PublicUser struct and newPublicUser(u user.User) converter in
api/handlers/auth/verificationHandler.go, exactly the JSON shape POST /v1/auth/verify already
returns: id, username, email, is_verified, created_at, updated_at
Given the public user struct and its converter, shared by the auth and user handlers from a
package under api/pkg (features/user_display_name.feature), exactly the JSON shape
POST /v1/auth/verify returns: id, username, email, is_verified, created_at, updated_at,
display_name and role
And this slice adds GET /v1/auth/me, handled by a new MeHandler (api/handlers/auth/meHandler.go)
built with NewMeHandler(container.GetUserUseCase), the same GetUserUseCase every other
protected handler already gets from api/dependecyInjection.go; no new use case or domain
@@ -42,23 +43,23 @@ Feature: A logged-in user fetches their own public profile without triggering th
Scenario: A verified user fetches their own profile
Given a user repository containing user id 7, username "alice", email "alice@example.com",
is_verified true, TokenVersion 0
is_verified true, role "owner", TokenVersion 0
And a valid jwt cookie for user id 7 encoding token_version 0
When the client sends GET /v1/auth/me with that cookie
Then the response status is 200
And the response header Cache-Control is "no-store"
And the response body is the user as JSON with id 7, username "alice", email
"alice@example.com", is_verified true
"alice@example.com", is_verified true, role "owner"
Scenario: An unverified user still fetches their own profile, with is_verified false, not a 403
Given a user repository containing user id 8, username "bob", email "bob@example.com",
is_verified false, TokenVersion 0
is_verified false, role "owner", TokenVersion 0
And a valid jwt cookie for user id 8 encoding token_version 0
When the client sends GET /v1/auth/me with that cookie
Then the response status is 200
And the response header Cache-Control is "no-store"
And the response body is the user as JSON with id 8, username "bob", email "bob@example.com",
is_verified false
is_verified false, role "owner"
Scenario: No jwt cookie at all is refused
Given a user repository containing user id 7, username "alice", is_verified true, TokenVersion 0
+6 -6
View File
@@ -37,13 +37,13 @@ wiring pattern in `test/stale_token_invalidation_http_test.go`.
## HTTP-level checks
8. Seed `mockUserRepo` with user id 7, username "alice", email "alice@example.com",
`IsVerified: true`, `TokenVersion: 0`. Mint a cookie for user 7 with `token_version: 0`.
`GET /v1/auth/me` → assert status `200`, `Cache-Control` header equals `"no-store"`, and the
decoded JSON body has `id: 7`, `username: "alice"`, `email: "alice@example.com"`,
`is_verified: true`.
9. Seed user id 8, username "bob", email "bob@example.com", `IsVerified: false`,
`IsVerified: true`, `Role: owner`, `TokenVersion: 0`. Mint a cookie for user 7 with
`token_version: 0`. `GET /v1/auth/me` → assert status `200`, `Cache-Control` header equals
`"no-store"`, and the decoded JSON body has `id: 7`, `username: "alice"`,
`email: "alice@example.com"`, `is_verified: true`, `role: "owner"`.
9. Seed user id 8, username "bob", email "bob@example.com", `IsVerified: false`, `Role: owner`,
`TokenVersion: 0`. Mint a matching cookie. `GET /v1/auth/me` → assert status `200` (not 403),
`Cache-Control: no-store`, and `is_verified: false` in the body.
`Cache-Control: no-store`, `is_verified: false` and `role: "owner"` in the body.
10. No `jwt` cookie at all against the router from step 6 → assert status `401` (produced by
`jwtauth.Authenticator` itself; don't assert an exact body for this case, same rationale as
`features/account_verification.qa.md` step 15).
+4 -3
View File
@@ -18,8 +18,9 @@ Feature: Home screen
Default, Empty and Error alike): icon plug, title "Connect your website", text "Your site
reads published articles from RenewCMS. Share this guide with whoever builds it.", and a
link "Open the guide" navigating to /integration
And a greeting reading "{greeting}, {username}" sits above the subtitle in every state
(Loading, Default, Empty and Error alike); it is computed from the session's username and
And a greeting reading "{greeting}, {name}" sits above the subtitle in every state
(Loading, Default, Empty and Error alike); name is the session's display name when it is
not empty and the session's username otherwise; it is computed from that name and
the device's local hour via Date.getHours(), needs no request of its own since the session
is already resolved by the app-boot flow before HomePage ever renders, and so never has its
own loading or error state
@@ -109,7 +110,7 @@ Feature: Home screen
second request made for either
Scenario Outline: The greeting matches the hour of day
Given the session's username is "marta"
Given the session's username is "marta" and it has no display name
And the device's local hour is <hour>
When the user views /home
Then the greeting above the subtitle reads "<greeting>, marta"
+189
View File
@@ -0,0 +1,189 @@
Feature: A verified user can invite another person by email, and the users list shows users and open invites
As a member of the shared RenewCMS workspace
I want to invite someone by email and see who has an account or a pending invite
So that they can later create their own account with exactly the same access, while
registration stays closed to everyone who was not invited
Background:
Given the workspace is shared: every verified user sees the same articles and the same list,
roles are owner and admin (features/user_roles.feature), and there is no way to remove a user
And POST /v1/user/invite and GET /v1/user/ are mounted in NewUserRouter, inside the group that
requires a valid jwt cookie, a current token_version and a verified user
And POST /v1/user/invite additionally requires the owner role (403
apperr.OwnerRequiredErrorMessage for an admin); GET /v1/user/ is open to every verified user
And wherever a scenario has verified user id 7 post an invite, user 7 is the owner
And an invite has an id, an email stored in lower case, a hashed code, an expires_at equal to
its creation time plus 3 days, an invited_by user id, a nullable accepted_at and a created_at
And the raw invite code is a uuid, hashed with the same hash.Hasher used for verification codes,
and only the hash is stored
And an invite's status is derived and never stored: pending when accepted_at is empty and
expires_at is in the future, expired when accepted_at is empty and expires_at is in the past,
accepted when accepted_at is set
And the users list item shape is: id, kind ("user" or "invite"), status, created_at, plus
username, display_name, email and role for a user, plus email for an invite; neither the
code, its hash, invited_by nor password fields ever appear
And error responses are plain text from http.Error, success responses are JSON
And the invite email uses the template "invitation" with data Host (the configured PublicURL),
VerificationCode (the raw code), Email (the invited address) and InvitedBy (the inviter's
display name, or their username when the display name is empty)
And the email subject is "<InvitedBy> invited you to RenewCMS"
And the link in the email is <Host>/invite/accept?c=<raw code>
And POST /v1/user/invite is rate-limited per client IP with the auth rate limiter
(AUTH_RATE_LIMIT_MAX_ATTEMPTS, AUTH_RATE_LIMIT_WINDOW_SECONDS), independently counted from
/login and /password-reset
Scenario: A verified user invites a new address
Given a user repository containing verified user id 7, who is the owner, username "marta", display_name ""
And an empty invite repository
And a valid jwt cookie for user id 7
When the client sends POST /v1/user/invite with body {"email": "Sam.Oliveira@Renew.example"}
Then the response status is 201
And the response body is a JSON object with exactly the keys id, kind, email, status, created_at
and expires_at, with kind "invite", email "sam.oliveira@renew.example" and status "pending"
And the response body contains no key named code, hashed_code, verification_code or password
And the invite repository holds one invite with email "sam.oliveira@renew.example",
invited_by 7, accepted_at empty and expires_at 3 days after created_at
And the stored code is the hash of the raw code, not the raw code
And exactly one email was sent to "sam.oliveira@renew.example" with template "invitation"
And that email's Host is the configured PublicURL, its VerificationCode is the raw code,
its Email is "sam.oliveira@renew.example" and its InvitedBy is "marta"
Scenario: The email names the inviter by display name when there is one
Given verified user id 7, username "ines", display_name "Ines Duarte"
When the client sends POST /v1/user/invite with body {"email": "lea.martin@renew.example"}
Then the response status is 201
And the email's InvitedBy is "Ines Duarte"
Scenario Outline: An invalid email is rejected before anything is stored or sent
Given verified user id 7 and a valid jwt cookie for user id 7
When the client sends POST /v1/user/invite with body <body>
Then the response status is <status>
And the invite repository is still empty
And no email was sent
Examples:
| body | status |
| {"email": "sam.oliveira@renew"} | 400 |
| {"email": ""} | 400 |
| {} | 400 |
| {"email": "not-an-email"} | 400 |
| not json | 400 |
Scenario: An address that already has an account is refused
Given verified user id 7 and a user "jonas" with email "Jonas@Renew.example"
When the client sends POST /v1/user/invite with body {"email": "jonas@renew.example"}
Then the response status is 409
And the response body is "This address already has an account."
And the invite repository is still empty
And no email was sent
Scenario: An address with a live pending invite is refused
Given verified user id 7 and a pending invite for "sam.oliveira@renew.example" expiring in 2 days
When the client sends POST /v1/user/invite with body {"email": "sam.oliveira@renew.example"}
Then the response status is 409
And the response body is "There's already a pending invite for this address."
And the invite repository still holds only the original invite, unchanged
And no email was sent
Scenario: An expired invite is replaced by a new one
Given verified user id 7 and an expired invite for "p.huber@gmail.com" that expired 1 hour ago
When the client sends POST /v1/user/invite with body {"email": "p.huber@gmail.com"}
Then the response status is 201
And the invite repository holds exactly one invite for "p.huber@gmail.com", pending, with a
new code, and the expired one no longer exists
And exactly one email was sent to "p.huber@gmail.com"
Scenario: A failed email removes the invite
Given verified user id 7 and the mail repository is set to fail its next Send
When the client sends POST /v1/user/invite with body {"email": "lea.martin@renew.example"}
Then the response status is 500
And the response body is "Couldn't send the invite. Try again in a moment."
And the invite repository is empty
When the failure is cleared and the client sends the same request again
Then the response status is 201
Scenario: A failed email does not restore a replaced expired invite
Given an expired invite for "p.huber@gmail.com" and the mail repository set to fail its next Send
When the client sends POST /v1/user/invite with body {"email": "p.huber@gmail.com"}
Then the response status is 500
And the invite repository holds no invite for "p.huber@gmail.com"
Scenario Outline: Only an authenticated, verified, current-token user can use the endpoints
Given the request is made <credentials>
When the client sends <method> <path>
Then the response status is <status>
And no invite was created and no email was sent
Examples:
| credentials | method | path | status |
| with no jwt cookie | POST | /v1/user/invite | 401 |
| with a jwt cookie of an unverified user | POST | /v1/user/invite | 403 |
| with a jwt cookie whose token_version is stale | POST | /v1/user/invite | 401 |
| with a jwt cookie of a verified admin | POST | /v1/user/invite | 403 |
| with no jwt cookie | GET | /v1/user/ | 401 |
| with a jwt cookie of an unverified user | GET | /v1/user/ | 403 |
Scenario: The invite endpoint is rate-limited
Given AUTH_RATE_LIMIT_MAX_ATTEMPTS is 2 for a window covering the whole test
When the client at IP "203.0.113.20" sends 2 valid POST /v1/user/invite requests
And then sends a 3rd
Then the 3rd response is 429 with body apperr.TooManyRequestsErrorMessage and a Retry-After header
And no invite was created and no email was sent for the 3rd request
And GET /v1/user/ from the same client is not rejected with 429
Scenario: The list shows users and open invites, newest first
Given verified user id 7 "marta" created 12 Mar 2026
And user "jonas" created 2 Apr 2026
And user "ines" with display_name "Ines Duarte" created 18 Jun 2026
And an expired invite for "p.huber@gmail.com" created 3 Aug 2026
And a pending invite for "sam.oliveira@renew.example" created 27 Sep 2026
And an accepted invite for "jonas@renew.example" created 1 Apr 2026
When the client sends GET /v1/user/ with a valid jwt cookie for user id 7
Then the response status is 200
And the response body is a JSON array of exactly 5 items in this order: the pending invite for
"sam.oliveira@renew.example", the expired invite for "p.huber@gmail.com", user "ines", user
"jonas", user "marta"
And the accepted invite is not listed
And the invite items have exactly the keys id, kind, email, status, created_at, with kind
"invite" and status "pending" or "expired"
And the user items have exactly the keys id, kind, username, display_name, email, role, status,
created_at, with kind "user" and status "accepted"
And each user item has its own email and a role
And no item has a key named password, password_reset_code,
verification_code, verification_expiration, password_reset_expiration, token_version,
code, hashed_code, invited_by or accepted_at
Scenario: With nobody invited the list contains only the registered user
Given only verified user id 7 "marta"
When the client sends GET /v1/user/ with a valid jwt cookie for user id 7
Then the response status is 200
And the response body is a JSON array of exactly one item, kind "user", username "marta",
status "accepted"
Scenario: An invite turns from pending to expired with time, without any stored status
Given an invite created 3 days and 1 minute ago that has not been accepted
When the client sends GET /v1/user/
Then that invite's status is "expired"
Scenario: Registration stays closed for uninvited people
Given a user repository containing one verified user
And a pending invite for "sam.oliveira@renew.example"
When the client sends POST /v1/auth/register with username "sam", password "hunter2example12",
email "sam.oliveira@renew.example"
Then the response status is 403
And the response body is exactly apperr.RegistrationClosedErrorMessage
And no user was created and no email was sent
Scenario: Registration on an empty instance is unchanged
Given the user repository is empty
When the client sends POST /v1/auth/register with username "bob", password "hunter2example12",
email "bob@example.com"
Then the response status is 200
And a verification email is sent with template "verification"
And no invite exists
Scenario: Inviting someone never changes GET /v1/auth/registration
Given a user repository containing one verified user
When a pending invite exists
Then GET /v1/auth/registration still reports registration closed
+103
View File
@@ -0,0 +1,103 @@
# QA procedure: invitations
Package: `test` (black-box). New fakes must have unique type names across the package:
`mockInviteRepo` (implements `invite.Repository` with an in-memory slice and a `failSwitch`),
plus a `fixedClock` only if the use case takes one. Reuse `mockUserRepo` and `stubHasher`
(`user_test.go`) and `mockMailRepo` (`mail_test.go`; `SentEmails` entries expose `Address`,
`Template`, `Data`; `fail.failNext("Send")`).
## Setup shared by every case
1. Call `validator.InitValidator()` once.
2. Use cases: `useCases.NewCreateInviteUseCase(userRepo, inviteRepo, &stubHasher{}, mailRepo,
"https://cms.example.com")` and `useCases.NewListUsersAndInvitesUseCase(userRepo, inviteRepo)`
(final names are the coder's; constructors take only domain interfaces).
3. Handler: `user.NewHandler(updateProfile, createInvite, listUsersAndInvites)` mounted on a fresh
`chi.NewRouter()` mirroring `NewUserRouter`: `jwtauth.Verifier` + `jwtauth.Authenticator` with
`jwtauth.New("HS256", []byte("test-secret"), nil)`, `RequireCurrentToken(getUser)`,
`RequireVerifiedUser(getUser)`, then `POST /invite` and `GET /`. `POST /invite` is also wrapped
in `RequireOwner(getUser)`, placed before the limiter. For the rate-limit case
wrap only `POST /invite` in `RequireOwner(getUser)` + `TrustedProxyRealIP(nil)` +
`NewRateLimiter(2, time.Minute)`.
Requests via `httptest`; jwt cookie built with the `user_id` and `token_version` claims as in
`test/verified_account_required_http_test.go`. No live server, no real SQLite, no real SMTP.
4. Seed users: verified id 7 "marta" with `Role: owner`; unverified id 8 for the 403 cases. Time is real: build
invites with `ExpiresAt`/`CreatedAt` relative to `time.Now()` and compare with a 5 s tolerance.
## POST /v1/user/invite
5. Body `{"email":"Sam.Oliveira@Renew.example"}`, cookie for 7 -> `201`. Decode into
`map[string]json.RawMessage`: the key set is exactly `id`, `kind`, `email`, `status`,
`created_at`, `expires_at`, with `kind`="invite", `email`="sam.oliveira@renew.example",
`status`="pending"; none of `code`, `hashed_code`, `verification_code`, `password`.
`inviteRepo` holds one invite: lower-case email, `InvitedBy==7`, `AcceptedAt` nil,
`abs(ExpiresAt - (CreatedAt+72h)) < 5s`, stored code == `"hashed:"+rawCode` (stubHasher) where
`rawCode` is taken from the mail data; the stored code is not equal to `rawCode`.
6. `mailRepo.SentEmails` has exactly one entry: `Address`, `Template=="invitation"`, data of the
invitation mail type with `Host=="https://cms.example.com"`, `Email` the invited address,
`InvitedBy=="marta"` and a uuid-shaped `VerificationCode`.
7. Inviter with `DisplayName:"Ines Duarte"` -> `InvitedBy=="Ines Duarte"`. Inviter with an
empty display name -> username.
8. Table for 400 (`{"email":"sam.oliveira@renew"}`, `{"email":""}`, `{}`, `{"email":"not-an-email"}`,
`not json`): status `400`, `inviteRepo` empty, `SentEmails` empty.
9. Existing user with email `"Jonas@Renew.example"`, invite `jonas@renew.example` -> `409`, body exactly the new
apperr constant "This address already has an account.", no invite, no mail. This case pins that
the match is case-insensitive.
10. Seed a pending invite (expires in 2 days) for the address -> `409`, body "There's already a pending
invite for this address.", the seeded invite unchanged (same code hash and expiry), no mail.
11. Seed an expired invite (expired 1 h ago) -> `201`; `inviteRepo` has exactly one invite for the address, with
a different code hash and an expiry about 3 days out; one mail sent.
12. `mailRepo.fail.failNext("Send")` -> `500`, body "Couldn't send the invite. Try again in a moment.",
`inviteRepo` empty. Repeat the same request without re-arming -> `201`. With a seeded expired invite and a
failing send -> `500` and no invite for that address remains.
13. Auth table (`POST`): no cookie -> `401`; cookie of unverified user 8 -> `403`; cookie with stale
`token_version` -> `401`; cookie of a verified admin (seeded with `Role: admin`) -> `403`, plain
text body exactly `apperr.OwnerRequiredErrorMessage`. Each asserts no invite and no mail.
14. Rate limit: limiter of 2 per minute, `RemoteAddr` `203.0.113.20:1234`, three valid POSTs -> `201`,
`201`, `429`; third body is exactly `apperr.TooManyRequestsErrorMessage`, has `Retry-After`, and adds no
invite or mail. `GET /` from the same address afterwards is not `429`.
## GET /v1/user/
15. Seed per the feature scenario (three users, an expired, a pending and an accepted invite, with the
stated `CreatedAt` values). `200`; decode as `[]map[string]json.RawMessage`. Assert length 5, order
(pending sam, expired p.huber, ines, jonas, marta), key sets exactly as specified: `id`, `kind`,
`username`, `display_name`, `email`, `role`, `status`, `created_at` for user items and `id`, `kind`,
`email`, `status`, `created_at` for invite items, accepted invite absent, and none of the forbidden
keys anywhere. Also assert the raw body string contains each accepted user's own email address.
16. Only user 7 -> array with exactly one `kind:"user"` item, status `accepted`.
17. Invite created 3 days + 1 minute ago -> `status:"expired"`; created 2 days ago -> `pending`;
with `AcceptedAt` set -> not listed.
18. Auth table (`GET`): no cookie -> `401`; unverified -> `403`.
## Use-case level (no HTTP)
19. `CreateInvite` on a repository holding a user with the same email -> `errors.Is(err, invite.ErrEmailHasAccount)`;
live pending invite -> `errors.Is(err, invite.ErrPendingInvite)` (sentinel names are the coder's).
A mail failure wraps the mail repository error and the `Delete` of the invite is called
(if `Delete` also fails, both errors are joined, as `CreateUser` does).
## Mailer (real embedded templates, no SMTP)
20. `mailer.MailRepository{}.Render("invitation", data)` with `Host:"https://cms.example.com"`,
`VerificationCode:"abc-123"`, `Email:"lea@example.com"`, `InvitedBy:"Ines Duarte"` returns subject
`"Ines Duarte invited you to RenewCMS"` and a body containing
`https://cms.example.com/invite/accept?c=abc-123`, `lea@example.com` and `Ines Duarte`.
An `InvitedBy` of `<b>x</b>` is HTML-escaped in body. Subjects for `verification` and `password-reset` are
unchanged, and an unknown template still gets the default subject.
21. `internal/infrastructure/mailer/templates/invitation.html` is byte-identical to
`docs/design/source/emails/invitation.html` (read both files and compare).
## Regression: registration (extends registration_gate_and_verification_email.qa.md)
22. With one verified user and a pending invite for `sam.oliveira@renew.example`, `POST /v1/auth/register` with that
email -> `403`, body exactly `apperr.RegistrationClosedErrorMessage`, no user created, no mail sent.
23. Empty user repository -> `POST /v1/auth/register` still `200` with a `jwt` cookie and one `verification`
mail, and `inviteRepo` untouched. `GET /v1/auth/registration` still reports closed when a verified user
and a pending invite exist.
## Manual verification (not exercised by the Go tests)
- Start the app once against a fresh SQLite file: the `invites` table exists (model registered in
`AutoMigrate` in `api/dependecyInjection.go`) and inviting persists across a restart.
- Send a real invitation through a real or sandboxed SMTP server: the subject line, the rendering in a mail
client (light and dark) and that the link `{PUBLIC_URL}/invite/accept?c=...` carries the raw code.
The screen the link opens is not designed and is out of scope, so the link will not resolve in the SPA yet.
- SPA copy for the 429 ("Too many invites. Wait a moment, then try again.") is a note for the later SPA
slice and is not tested here. The SPA keys list rows by kind and id, since a user and an invite can share
a numeric id.
- Layering check by review: use cases import only `internal/domain/*`; the mailer subject logic lives in
`internal/infrastructure/mailer`.
+205
View File
@@ -0,0 +1,205 @@
Feature: The owner can cancel a pending invite and renew a pending or expired one
As the owner of the shared RenewCMS workspace
I want to cancel an invite I no longer want, or renew one that is stale or expired
So that only the people I currently intend to invite can create an account
Background:
Given the invite domain, the invitation email and the roles are those of features/invitations.feature
and features/user_roles.feature
And DELETE /v1/user/invite/{id} and POST /v1/user/invite/{id}/renew are mounted in NewUserRouter,
in the same group as POST /v1/user/invite: valid jwt cookie, current token_version, verified user,
owner role, trusted-proxy real IP, then the auth rate limiter
And the checks run in this order: 401, 403 unverified, 403 not owner, 429, 400 invalid id, 404, 409,
then the action
And user 7 "marta" is the verified owner and user 9 "jonas" is a verified admin
And error responses are plain text from http.Error, and the messages are:
| case | status | body |
| unknown invite | 404 | Invite not found |
| invite already accepted | 409 | This invite has already been accepted. |
| id is not a uint32 | 400 | apperr.IdUint32ErrorMessage |
| not the owner | 403 | Only the owner can do this. |
| no valid session | 401 | apperr.UnauthorizedErrorMessage |
| rate limited | 429 | apperr.TooManyRequestsErrorMessage |
| renew email not sent | 500 | Couldn't send the invite. Try again in a moment. |
And the renew response has the same shape as the create response: exactly the keys id, kind
("invite"), email, status, created_at and expires_at
Rule: Cancelling an invite
Scenario: The owner cancels a pending invite
Given an invite id 3 for "sam.oliveira@renew.example", pending, created by user 7
And a valid jwt cookie for user 7
When the client sends DELETE /v1/user/invite/3
Then the response status is 204
And the response body is empty
And the invite repository no longer holds invite 3
And no email was sent
And GET /v1/user/ no longer lists the invite
Scenario: A cancelled invite's link stops working
Given invite 3 was cancelled by the owner
When the client sends GET /v1/auth/invite?c=<the code from that invite>
Then the response status is 404
And the response body is "This invite link doesn't work."
And accepting the invite with that code returns 404, creates no user and sets no cookie
Scenario: A cancelled address can be invited again
Given invite 3 for "sam.oliveira@renew.example" was cancelled
When the owner sends POST /v1/user/invite for that address
Then the response status is 201
Scenario: The owner cancels an expired invite
Given invite 4 is expired
When the owner sends DELETE /v1/user/invite/4
Then the response status is 204
And the invite repository no longer holds invite 4
Scenario: Other invites and users are untouched
Given invites 3 and 4 and users 7 and 9
When the owner cancels invite 3
Then invite 4 and users 7 and 9 are unchanged
Scenario: An unknown invite is not found
When the owner sends DELETE /v1/user/invite/999
Then the response status is 404
And the response body is "Invite not found"
Scenario: Cancelling twice is not found
Given the owner cancelled invite 3
When the owner sends DELETE /v1/user/invite/3 again
Then the response status is 404
Scenario: An accepted invite cannot be cancelled
Given invite 5 was accepted and its user exists
When the owner sends DELETE /v1/user/invite/5
Then the response status is 409
And the response body is "This invite has already been accepted."
And invite 5 and its user remain
Rule: Renewing an invite
Scenario: The owner renews an expired invite
Given invite 4 for "lea.martin@renew.example", created 5 days ago, expired 2 days ago,
invited_by 7, stored code hash "hashed:OLD-CODE"
And a valid jwt cookie for user 7
When the client sends POST /v1/user/invite/4/renew
Then the response status is 200
And the response has Cache-Control "no-store"
And the response id is 4, kind "invite", email "lea.martin@renew.example" and status "pending"
And created_at is now and expires_at is 3 days after created_at, each within 5 seconds
And the response body has no key named code, hashed_code, invited_by or accepted_at
And the invite repository holds exactly one invite for that address, with id 4, a new code hash,
invited_by 7 and accepted_at empty
Scenario: The owner renews a pending invite
Given invite 3 is pending
When the owner sends POST /v1/user/invite/3/renew
Then the response status is 200
And invite 3 has a new code hash and created_at now
Scenario: A renewed invite moves to the top of the users list
Given invite 3 is pending and older than invite 6
When the owner renews invite 3
Then GET /v1/user/ lists invite 3 before invite 6
Scenario: The old link is dead and the new link works
Given invite 4 was renewed and the raw code in the new email is NEW-CODE
When the client sends GET /v1/auth/invite?c=<the old code>
Then the response status is 404
And accepting with the old code returns 404 and creates no user
And GET /v1/auth/invite?c=NEW-CODE returns 200 with {"email": "lea.martin@renew.example"}
And this holds when the renewed invite was pending as well as expired
Scenario: Renewing sends the invitation email again
When the owner renews invite 4
Then exactly one email was sent, with template "invitation"
And its Host is the configured PublicURL, its Email is the invited address, its InvitedBy is
the acting owner's display name or, when empty, username
And its VerificationCode is the new raw code
And the link in it is <Host>/invite/accept?c=<new raw code>
And the invite's invited_by is unchanged
Scenario: An unknown or cancelled invite is not found
When the owner sends POST /v1/user/invite/999/renew
Then the response status is 404
And the response body is "Invite not found"
And renewing a cancelled invite also returns 404
Scenario: An accepted invite cannot be renewed
Given invite 5 was accepted
When the owner sends POST /v1/user/invite/5/renew
Then the response status is 409
And the response body is "This invite has already been accepted."
And invite 5 is unchanged and no email was sent
Scenario: A failed email leaves the invite as it was
Given expired invite 4 and an email repository whose next send fails
When the owner sends POST /v1/user/invite/4/renew
Then the response status is 500
And the response body is "Couldn't send the invite. Try again in a moment."
And invite 4 keeps its old code hash, expires_at and created_at, and is still expired
And a pending invite whose renew mail fails keeps its old link valid
And a retry of the same request returns 200
Rule: Only the owner can manage invites
Scenario Outline: Access is checked on both endpoints
Given invite 3 is pending
When <caller> sends <method> <path>
Then the response status is <status>
And invite 3 is unchanged
And no email was sent
Examples:
| caller | method | path | status |
| a client with no cookie | DELETE | /v1/user/invite/3 | 401 |
| a client with no cookie | POST | /v1/user/invite/3/renew | 401 |
| a stale token_version | DELETE | /v1/user/invite/3 | 401 |
| a stale token_version | POST | /v1/user/invite/3/renew | 401 |
| an unverified user | DELETE | /v1/user/invite/3 | 403 |
| an unverified user | POST | /v1/user/invite/3/renew | 403 |
| verified admin 9 | DELETE | /v1/user/invite/3 | 403 |
| verified admin 9 | POST | /v1/user/invite/3/renew | 403 |
Scenario: An admin is refused with the owner message, even on an unknown id
When admin 9 sends DELETE /v1/user/invite/999
Then the response status is 403
And the response body is "Only the owner can do this."
Scenario Outline: An id that is not a uint32 is rejected
When the owner sends <method> <path>
Then the response status is 400
And the response body is apperr.IdUint32ErrorMessage
Examples:
| method | path |
| DELETE | /v1/user/invite/abc |
| DELETE | /v1/user/invite/-1 |
| DELETE | /v1/user/invite/4294967296 |
| POST | /v1/user/invite/abc/renew |
| POST | /v1/user/invite/-1/renew |
| POST | /v1/user/invite/4294967296/renew|
Rule: Rate limiting
Scenario: Requests over the limit are refused
Given the auth rate limiter allows 2 requests per window
When the owner sends three valid requests to DELETE or renew from IP 203.0.113.40
Then the third response is 429 with apperr.TooManyRequestsErrorMessage and a Retry-After header
And the third request changes nothing and sends no email
And GET /v1/user/ from the same address is not 429
Scenario: An admin does not use up the quota
When admin 9 sends three requests from one IP
Then all three responses are 403, not 429
Scenario: The counter is shared with inviting
Given the auth rate limiter allows 2 requests per window
When the owner sends POST /v1/user/invite, then renews an invite, then sends DELETE /v1/user/invite/3
Then the DELETE returns 429
Rule: Existing behaviour is unchanged
Scenario: The invitation and acceptance features still hold
Then every scenario of features/invitations.feature and features/accept_invitation.feature still passes
+71
View File
@@ -0,0 +1,71 @@
# QA procedure: invite management
Package: `test` (black-box). Reuse `mockUserRepo`, `stubHasher`, `mockMailRepo` and `mockInviteRepo`.
Extend `mockInviteRepo` with the new renew method and a `failSwitch` entry for it (unique type names
across the package). No live server, no real SQLite (except case 27), no real SMTP.
## Setup shared by every case
1. Call `validator.InitValidator()` once.
2. Use cases over domain interfaces only: `CreateInvite`, `ListUsersAndInvites`, `GetInvite`, the accept
use case, plus the new cancel and renew use cases (final names are the coder's).
3. Handler built with `NewHandler(...)` on a fresh `chi.NewRouter()` mirroring `NewUserRouter`:
`jwtauth.Verifier` + `jwtauth.Authenticator` (`jwtauth.New("HS256", []byte("test-secret"), nil)`),
`RequireCurrentToken`, `RequireVerifiedUser`, `GET /`, then a group with `RequireOwner`,
`TrustedProxyRealIP(nil)` and `NewRateLimiter` containing `POST /invite`, `DELETE /invite/{id}` and
`POST /invite/{id}/renew`. Mount `GET /invite` and `POST /invite/accept` from the auth handler for the
old-link cases.
4. Seed users: owner 7 "marta", unverified 8, admin 9. Invite hashes are `"hashed:"+raw`. Times are
relative to `time.Now()`, compared with a 5 s tolerance.
## DELETE /v1/user/invite/{id}
5. Pending invite, owner cookie -> `204`, empty body, invite gone, no mail, absent from `GET /`.
6. After cancel: `GET /invite?c=<code>` -> `404`; accept -> `404`, no user, no cookie; re-invite the address -> `201`.
7. Expired invite -> `204`.
8. Unknown id -> `404` "Invite not found"; second delete -> `404`.
9. Accepted invite -> `409` "This invite has already been accepted."; invite and user remain.
10. Other invites and users unchanged after a cancel.
11. Repository delete failure -> `500`, invite still present.
## POST /v1/user/invite/{id}/renew
12. Expired invite -> `200`, `Cache-Control: no-store`; key set exactly `id`, `kind`, `email`, `status`,
`created_at`, `expires_at`; no `code`, `hashed_code`, `invited_by`, `accepted_at`.
13. Stored invite: same id, new hash, `invited_by` 7, `accepted_at` nil, `created_at` about now,
`expires_at` = `created_at` + 72h.
14. Pending invite renews with `200`, new hash.
15. Mail: exactly one entry, template `invitation`, `Host`, `Email`, `InvitedBy` by display name or username
of the acting owner, `VerificationCode` = raw new code.
16. `GET /` lists the renewed invite first.
17. Old code: `GET /invite` and accept -> `404`, no user; new code -> `200` with the email. Control checks before
the renew show the old code worked. Same for pending.
18. Unknown id -> `404`; cancelled id -> `404`.
19. Accepted -> `409`, all fields unchanged, no mail.
20. `mailRepo.fail.failNext("Send")` -> `500` "Couldn't send the invite. Try again in a moment."; invite hash,
expiry and created_at unchanged; retry -> `200`.
21. Renew persistence failure -> `500`, no mail, invite unchanged.
## Access and ids (table over both endpoints)
22. No cookie -> `401`; stale `token_version` -> `401`; unverified -> `403`; admin -> `403` with body
`apperr.OwnerRequiredErrorMessage`; admin on an unknown id -> `403`. Each: invite unchanged, no mail.
23. Ids `abc`, `-1`, `4294967296` -> `400` `apperr.IdUint32ErrorMessage` on both endpoints.
## Rate limit
24. Limiter of 2, `RemoteAddr` `203.0.113.40:1234`: third request -> `429`, `apperr.TooManyRequestsErrorMessage`,
`Retry-After`, no change, no mail. `GET /` from the same address is not `429`.
25. Admin's three requests -> `403`, `403`, `403`.
26. Shared counter: `POST /invite`, renew, then `DELETE` -> `429`.
## Use case and persistence
27. Use case level:
- unknown id -> `errors.Is(err, ErrInviteNotFound)`; accepted -> the accepted sentinel (name is the coder's);
- success returns the same id, a new hash, `CreatedAt` about now, `ExpiresAt` = `CreatedAt` + `invite.Lifetime`;
- mail failure wraps `ErrInviteEmailNotSent` and restores the prior values;
- the mail logic is shared with `CreateInvite`.
28. Persistence on in-memory SQLite: the renew method updates hash, expiry and created_at by id, returns
`ErrInviteNotFound` when the row is missing or already accepted.
## Manual
Renew against a real or sandboxed SMTP server: one mail arrives, the new link works, the old mail's link is dead.
Persistence across a restart on a fresh SQLite file. Review layering and that no comments were introduced.
## Out of scope
SPA handling of 404, 409 and 429 on these endpoints: this slice is API-only.
+215
View File
@@ -0,0 +1,215 @@
Feature: The multi-user flows hold up under concurrency, failures and edge input
As the maintainer of RenewCMS
I want the invitation, account-menu and password-reset flows to be safe under concurrent use,
server failures and unusual input
So that a closed registration cannot be bypassed, no address is revealed, and nobody is left
with a spinner or a lost focus
Background:
Given this pass adds no endpoint, no route, no response shape and no design change
And every item below is covered by a test that fails before the change and passes after it,
or is stated as not testable
And error responses are plain text from http.Error, success responses are JSON
And the layering rule holds: domain has no GORM or HTTP, use cases see only domain
interfaces, handlers see only use cases, and no comment is added anywhere
Rule: Accepting an invite is atomic
Background:
Given the persistence tests run against a real in-memory SQLite database migrated with the
same models as api/dependecyInjection.go, not a fake repository
And marking an invite accepted is a conditional update on the invite row with
accepted_at IS NULL, and the number of rows affected is checked
And the conditional update and the user insert run in one database transaction, so both
commit or neither does
And no domain, use case or handler code knows about the transaction: the use case calls a
domain repository method and the persistence implementation owns the transaction
Scenario: Two concurrent accepts of one code create exactly one user
Given a pending invite for "lea.martin@renew.example" with raw code "3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42"
When two clients at the same moment send POST /v1/auth/invite/accept with that code, one
with username "lea" and one with username "lea2", both with password "limewash2026"
Then exactly one response is 200 with a jwt cookie
And the other response is 404 with body "This invite link doesn't work." and no jwt cookie
And the users table holds exactly one user with email "lea.martin@renew.example"
And the invite has accepted_at set
Scenario: The concurrency test is repeatable
Given the two-accept scenario above
When it runs 50 times, each on a fresh database
Then every run ends with exactly one user and one 200
Scenario: A used code loses at the conditional update, not at the earlier lookup
Given a pending invite that another accept marks accepted after this accept has read it
but before it marks it
When this accept marks the invite
Then zero rows are affected and the accept fails with the same invite-not-found error a
used code gives
And the response is 404 with body "This invite link doesn't work."
And no user was inserted for this accept
Scenario: A failed user insert leaves the invite pending
Given a pending invite for "lea.martin@renew.example"
And a verified user "marta"
When an accept with username "marta" is sent
Then the response is 409 with body "That username is taken. Try another."
And the invite is still pending, with accepted_at empty
Scenario: A failed invite update leaves no user behind
Given a pending invite for "lea.martin@renew.example"
And the conditional update fails after the user insert has been attempted in the transaction
When the accept runs
Then the transaction rolls back and no user "lea" exists
And the invite is still pending
And the response is 500 and no jwt cookie is set
Scenario: The existing accept behaviour is unchanged
Given the scenarios of features/accept_invitation.feature
Then all of them still pass, except that a failure marking the invite accepted no longer
makes the use case call userRepository.Delete: the rollback replaces the compensating delete
Rule: The accept screen recovers from a failed invite lookup
Background:
Given the route /invite/accept?c=CODE of docs/design/screens/accept-invite.md
And the design has a "Server error" state for the submit only, so the failed lookup is a
new state approved by the user, with no board frame
Scenario Outline: A failed lookup shows a server-error alert with a Try again action
Given the SPA is at /invite/accept?c=abc123
When GET /v1/auth/invite?c=abc123 <outcome>
Then the "Checking your invite…" spinner is replaced by an Alert (error, circle-x) with
title "Couldn't check your invite" and text "Something went wrong on the server. Try again in a moment."
And a "Try again" button is visible
And no form, no Email field and no ResultPanel is shown
And the spinner is not shown
Examples:
| outcome |
| answers 500 |
| answers 502 |
| fails with a network error |
Scenario: Try again looks the invite up again
Given the failed-lookup alert is shown
When the person activates "Try again"
Then the "Checking your invite…" spinner is shown and GET /v1/auth/invite?c=abc123 is sent again
And when it answers 200 {"email": "lea.martin@renew.example"} the Default state is shown
Scenario: Try again failing again shows the alert again
Given the failed-lookup alert is shown
When the person activates "Try again" and the lookup fails again
Then the alert is shown again and the button is enabled
Scenario Outline: Other lookup outcomes keep their design states
When GET /v1/auth/invite?c=abc123 answers <status>
Then the design state "<state>" is shown
Examples:
| status | state |
| 404 | Invalid or used link (404) |
| 410 | Expired link (410) |
Rule: The reset-request 200 stays generic when the mail fails
Scenario: A failed send is logged and the response is unchanged
Given the user repository contains a user "alice" with email "alice@example.com"
And the mail repository is set to fail on Send with the error "smtp: connection refused"
When the client sends POST /v1/auth/password-reset with body {"email": "alice@example.com"}
Then the response status is 200
And the response body is {"message": "If an account exists for that email, a password reset link has been sent."}
And no jwt cookie is set
And the process log contains a line naming the failed send and the error "smtp: connection refused"
Scenario: The response is identical for a failed send, a successful send and an unknown email
Given three requests: alice with a failing mailer, alice with a working mailer, and an unknown address
Then the status, the body and the response headers other than Date are the same in all three
Scenario: The log does not contain the raw reset code
Given the same failing send
Then the process log contains neither the raw code nor its hash
Rule: The invite email is validated identically in the SPA and the Go validator
Background:
Given the Go rule is the validate tag of the invite request struct checked with
validator.Validate.Struct, extended through validator.InitValidator, not by hand
And the SPA rule is the InviteUserModal pattern
And the accepted and rejected addresses are the single table below
And user@localhost is rejected in both
Scenario Outline: The same address gets the same verdict on both sides
When POST /v1/user/invite is sent with body {"email": "<email>"} by a verified user
And the same address is typed in the invite modal
Then the API answers <status>
And the modal shows "<modal>"
Examples:
| email | status | modal |
| sam.oliveira@renew.example | 201 | no error |
| Sam.Oliveira@Renew.example | 201 | no error |
| sam+news@renew.example | 201 | no error |
| sam@mail.renew.example | 201 | no error |
| user@localhost | 400 | Enter a full email address, like name@example.com. |
| sam@renew | 400 | Enter a full email address, like name@example.com. |
| sam@.renew.example | 400 | Enter a full email address, like name@example.com. |
| sam@renew..example | 400 | Enter a full email address, like name@example.com. |
| sam@renew.example. | 400 | Enter a full email address, like name@example.com. |
| sam @renew.example | 400 | Enter a full email address, like name@example.com. |
| @renew.example | 400 | Enter a full email address, like name@example.com. |
| not-an-email | 400 | Enter a full email address, like name@example.com. |
| | 400 | Enter a full email address, like name@example.com. |
Scenario: A rejected address stores nothing and sends nothing
When POST /v1/user/invite is sent with body {"email": "user@localhost"}
Then no invite was created and no email was sent
Rule: The mobile account sheet keeps its chip state and focus
Background:
Given the account chip (aria-haspopup "menu", title "Account") of docs/design/components.md
and the account menu of docs/design/screens/profile.md, shown as a sheet on mobile (390 px)
And there is no visual change: the sand fill while open is unchanged
Scenario Outline: The chip's aria-expanded tracks the sheet
Given the chip is visible and the sheet is closed
Then the chip has aria-expanded "false"
When the person activates the chip
Then the sheet is open and the chip has aria-expanded "true"
When the sheet closes by <closing action>
Then the chip has aria-expanded "false"
Examples:
| closing action |
| pressing Escape |
| tapping the backdrop |
| activating "Profile" |
Scenario Outline: Focus returns to the opener when the sheet closes
Given the sheet was opened from the chip
When the sheet closes by <closing action>
Then focus returns to the chip if it is still mounted, otherwise to the navbar toggle
Examples:
| closing action |
| pressing Escape |
| tapping the backdrop |
| activating "Profile" |
Scenario: Logging out does not try to focus a removed chip
Given the sheet is open
When the person activates "Log out"
Then the session ends and no error is thrown
Scenario: Focus is not stolen when the sheet was never opened
Given the page has just loaded
Then focus is not on the chip
Rule: userRepository.Delete deletes through the persistence model
Scenario: Deleting a user removes only that row
Given a real in-memory SQLite database with users 1, 2 and 3
When Delete is called for user 2
Then user 2 is gone and users 1 and 3 remain
And Delete goes through the persistence model, not the domain struct
+63
View File
@@ -0,0 +1,63 @@
# QA procedure: multi-user hardening
Two parts. Go tests in `test/` (package `test`, black-box). Vitest for the SPA. Every item is written so it fails first.
## Part A. Go
### A1. Atomic accept (real in-memory SQLite, no fake)
1. Open a real GORM SQLite database with a shared-cache in-memory DSN (or a `t.TempDir()` file if shared memory is flaky on Windows), migrated with the same models as `api/dependecyInjection.go`. Build the real persistence repositories, the real accept use case and the handler on a fresh `chi.NewRouter()`. `validator.InitValidator()`, `jwtauth.New("HS256", []byte("test-secret"), nil)`, `httptest`. Package-unique type names.
2. Do not use `SetMaxOpenConns(1)`: it serialises the requests and hides the race. Two connections must truly contend.
3. Seed one pending invite with the real hasher's hash of raw code `3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42`, email `lea.martin@renew.example`.
4. Start two goroutines behind a `sync.WaitGroup` and a start channel, one POST with username `lea`, one with `lea2`. Collect both recorders.
5. Assert: exactly one 200 with a `jwt` cookie; the other 404 with body exactly the invite-invalid message and no `Set-Cookie`; one user with that email; invite `accepted_at` not null.
6. Repeat 50 times, each on a fresh DB. It must fail before the change.
7. Rollback case: force the invite update to fail (a `BEFORE UPDATE` trigger with `RAISE(ABORT, ...)` on invites). POST gives 500, no user `lea`, invite still pending, no cookie.
8. Taken username: seed user `marta`, POST username `marta` gives 409 with the username-taken message, invite `accepted_at` still null.
9. Zero rows affected: a thin decorator over the real repository marks the invite accepted in SQL between lookup and update. Expect the invite-not-found sentinel via `errors.Is` and no user.
10. Re-run the existing accept-invitation cases. The case asserting `Delete` after a failing mark-accepted is rewritten to assert no user is left.
### A2. userRepository.Delete via the persistence model
11. Against the same real SQLite: create users 1 to 3, `Delete(2)`, assert row 2 gone and 1 and 3 remain. Keep the existing behaviour for a missing id.
12. If step 11 passes before the refactor, report "no failing test possible, internal refactor only". Do not fabricate a failing test.
### A3. Password reset send failure
13. Handler over the real reset-request use case, `mockUserRepo` holding alice, a mail fake failing with `errors.New("smtp: connection refused")`.
14. Capture the standard log with `log.SetOutput(&buf)`, restore with `t.Cleanup`. No parallel tests.
15. POST `{"email":"alice@example.com"}` gives 200, body exactly the generic message JSON, no `Set-Cookie`. `buf` names the send failure and `smtp: connection refused`, and contains neither the raw code nor its hash.
16. Compare failing mailer, working mailer and unknown email: same status, body and headers except `Date`.
### A4. Invite email validation (Go side)
17. Table from the feature. POST `/v1/user/invite` with a verified user's `jwt` cookie. Accepted gives 200; rejected gives 400, no invite stored, no email sent. `user@localhost` is rejected.
18. Share the table between the Go and Vitest suites through one JSON fixture so they cannot drift. Location is the coder's call.
## Part B. SPA (Vitest + Vue Test Utils, `task test:web`)
### B1. Accept screen, failed lookup
| Mock | Expected |
| --- | --- |
| GET /v1/auth/invite?c=abc123 gives 500 | Alert title "Couldn't check your invite", text "Something went wrong on the server. Try again in a moment.", button "Try again", no spinner, no form |
| gives 502 | same |
| network error | same |
| gives 404 | ResultPanel unchanged |
| gives 410 | ResultPanel unchanged |
19. Try again: click, assert a second GET and the spinner; second mock answers 200 `{email:'lea.martin@renew.example'}` and the Default state shows. A second failure shows the alert again.
20. Existing accept-screen specs pass unchanged.
### B2. Invite modal email
21. Feed each row of the shared table into the invite modal, blur, assert the error text or none and the submit state.
### B3. Mobile account sheet
22. Mount at the mobile branch, attach to `document.body`. Chip `aria-expanded` is "false", then "true" after click, then "false" after each close (Escape, backdrop, Profile), with focus on the chip, or on the navbar toggle when the drawer chip is unmounted. Log out throws nothing. Await `nextTick` and the leave transition before asserting focus.
## Visual (`task visual:check -- accept-invite`)
- The failed-lookup state has no board frame. The user approved a per-state `exception` (`approvedBy` the user) for it in `web/visual/states.ts`.
- All existing accept-invite states stay within 10 %.
- The sheet fix is not a visual change. Re-run the screens containing the sheet at mobile in light and dark to confirm nothing moved.
## Manual verification
- Unreachable SMTP host on password reset returns 200 and the server log shows the error.
- Real file SQLite: two concurrent accepts against a running binary leave one user.
- Screen reader: chip announces expanded and collapsed; focus lands on the chip after closing the sheet.
## Docs (no scenario)
- `docs/architecture.md` lacks `api/handlers/user` and `api/pkg/publicuser`; coder adds both.
+5 -4
View File
@@ -130,13 +130,14 @@ Feature: Nuxt UI shell foundation and router guards
Then the alert above the title contains "Your session expired."
And the footer area outside the card contains a "Forgot password?" link
Scenario: DashboardShell renders the three navigation destinations
Scenario: DashboardShell renders the five navigation destinations
Given the current route is /article
When DashboardShell mounts
Then the sidebar navigation lists exactly three destinations: "Home" linking to /home, "Articles"
linking to /article, and "Integration" linking to /integration
Then the sidebar navigation lists exactly five destinations in this order: "Home" linking to
/home, "Articles" linking to /article, "Users" linking to /users, "Integration" linking
to /integration, and "Settings" linking to /settings
And the "Articles" destination has aria-current="page"
And neither "Home" nor "Integration" has aria-current set
And none of "Home", "Users", "Integration" and "Settings" has aria-current set
Scenario: DashboardShell shows the offline banner when the browser reports offline
Given navigator.onLine is false
+2 -2
View File
@@ -41,7 +41,7 @@ Mock `useApi` / the `/v1/auth/me` call per case; no real backend, no httptest se
13. **AuthShell notice/footer slots** — mount AuthShell with notice and footer slot content; assert
both render outside/above the card content as specified.
14. **DashboardShell nav + aria-current** — mount DashboardShell with current route /article; assert
3 links (Home→/home, Articles→/article, Integration→/integration), and only the Articles link
5 links in order (Home→/home, Articles→/article, Users→/users, Integration→/integration, Settings→/settings), and only the Articles link
has aria-current="page".
15. **DashboardShell offline banner** — mock navigator.onLine false, mount DashboardShell; assert
the offline banner is visible; set navigator.onLine true and dispatch the 'online' event; assert
@@ -57,7 +57,7 @@ plus the components.md AuthShell/DashboardShell sections.
- [ ] AuthShell below sm: card loses border, 20px padding fills screen, fields/buttons use xl size,
light and dark.
- [ ] AuthShell footer: UColorModeSelect size="sm" plus footer links render outside the card.
- [ ] DashboardShell desktop: sidebar with RenewCMS logo header, 3 nav items, UserMenu footer;
- [ ] DashboardShell desktop: sidebar with RenewCMS logo header, 5 nav items, UserMenu footer;
collapsing the sidebar leaves a 56px icon rail with tooltips on hover/focus.
- [ ] DashboardShell mobile (below lg): UDashboardSidebarToggle appears, sidebar becomes a
slideover, closes after navigating.
+454
View File
@@ -0,0 +1,454 @@
Feature: Profile page, display name and the account menu
As a verified RenewCMS user in the shared workspace
I want /profile to let me set an optional display name, see my read-only account details and
email myself a password reset link, and I want the sidebar account chip to open a menu that
leads there
So that people are named by a human name across the back-office, while logging in still uses the
username, and I always have a way to reach Profile, switch theme and log out
Background:
Given /profile is a verified route (meta.auth "verified", meta.title "Profile") rendered as
ProfilePage inside DashboardShell, per docs/design/routes.md and docs/design/screens/profile.md
And the endpoints already exist and this slice wires the SPA to them with no Go change:
GET /v1/auth/me (returns id, username, email, is_verified, display_name), PATCH /v1/user/me
(features/user_display_name.feature) and POST /v1/auth/password-reset
(features/request_password_reset.feature)
And useApi's getMe and the Session type gain email and displayName; a missing or null
display_name in a response is read as ""; the session store gains an action that replaces
the session's displayName from the display_name of a PATCH /v1/user/me response
And the PageHeader shows breadcrumb "Profile" (mobile title "Profile"), the page title
"Profile" and the subtitle "Your account on this RenewCMS workspace."; none of the five
navigation items (Home, Articles, Users, Integration, Settings) has aria-current="page" on /profile
And the page is at most 720 px wide with three ProfileCards in this order: Display name,
Account, Password; cards are separated by 20 px, have 20 px padding (16 px on mobile) and
inputs are 40 px high (44 px on mobile, 16 px text)
And the Display name card has the title "Display name", the text "Shown instead of your
username across the back-office and in the emails RenewCMS sends. Leave it empty to use your
username.", one input labelled "Display name (optional)" with placeholder "e.g. Marta Alves",
and a help row under the input: the field error on the left (icon circle-alert, 12 px, error
color) and the counter "n / 60" on the right in the mono style; there is no maxlength, so
typing past 60 is possible and shows the error
And the Display name card's footer strip (top border, --ui-bg-muted, 12 px status text on the
left, Save button on the right, 32 px high on desktop and 44 px on mobile) shows "Unsaved
changes" in the warning color while the draft is dirty and no save is in flight; otherwise
it shows "You appear as “{display name}”." when a display name is saved, or "You appear as
“{username}”, your username." when none is
And the draft is the trimmed field value (String.prototype.trim); it is dirty when it differs
from the session's displayName; it is valid when its length counted in Unicode code points
(Array.from(value).length, the same count as the API's utf8.RuneCountInString, not bytes,
not UTF-16 units and not grapheme clusters) is 60 or fewer; the counter shows that count
and turns red (error color) above 60
And Save is enabled (full opacity) while the draft is dirty and valid, or while a save is in
flight; otherwise it is disabled at 40 % opacity; pressing Enter in the field activates Save
only when Save is enabled, and does nothing otherwise
And activating Save sends PATCH /v1/user/me with JSON {"display_name": "<trimmed draft>"};
while it is in flight the field is disabled and dimmed, the button reads "Saving…" with a
loader-circle icon, and a second submit is ignored
And a 200 response replaces session.displayName with the response's display_name at once (the
server's value, not the typed one), sets the field to that value, and raises a toast:
color success, icon i-lucide-circle-check, id "display-name-saved", title "Display name
saved", description "You now appear as {display name} across RenewCMS and in emails."
And the display name is shown wherever a person is named, read from the session: the sidebar
chip and the account menu (name and initials) and the Home greeting "{greeting}, {name}",
where name is the display name when not empty and the username otherwise; the Users list
reads display_name from its own GET /v1/user/ items and is not changed by this slice
And any non-2xx or failed PATCH keeps the typed value and the dirty state; a 401 and a 403
are handled entirely by useApi's global handling
(features/api_client_global_error_handling.feature)
And the Account card has the title "Account", the text "Set when your account was created. You
log in with your username, even after adding a display name.", and two disabled inputs with
a lock icon at the right: "Username" (the session's username) and "Email" (the session's
email), in two columns on desktop (minmax(0,1fr) minmax(0,1.4fr)) and stacked on mobile
And the Password card has the title "Password", the text "To change it, we'll email a reset
link to {email}. The link works once, within 1 hour.", a disabled input labelled "Password"
showing "••••••••••••" with a lock icon, and, beside it (stacked on mobile), a secondary
button "Send reset link" with the mail icon; the note under them exists only once a request
has been made
And activating the button sends POST /v1/auth/password-reset with JSON {"email": "<session
email>"}, with no confirmation step; while in flight the button reads "Sending…" with a
loader-circle icon and is disabled; the note is role="status", 16 px icon, 600-weight title
and the text on a soft background
And leaving /profile while the draft is dirty (a route change, including Log out) opens a
ConfirmDialog, except when the redirect is caused by a 401 handled by useApi
(authRedirectPending); leaving while the draft is not dirty, or after a successful save,
opens nothing
And the UserMenu chip in the sidebar footer no longer logs out on click: it opens the account
menu; the chip is 40 px high with a 26 px sand (#d4c5b0) initials avatar with ink text, the
name (display name, else username) with truncation, and a chevrons-up-down icon; it has
aria-haspopup="menu", aria-expanded reflecting the open state, and title "Account"
And while the menu is open, or while the current route is /profile, the chip takes --rc-sand
with #111111 text
And on desktop (lg and up) the menu is a 224 px popover above the chip aligned to its left
edge with --rc-shadow-pop; below lg the account row in the navigation drawer closes the
drawer and opens the menu as a bottom sheet with a grab handle over an --rc-overlay scrim;
Escape or a click outside closes either, and focus returns to the chip; arrow keys move
between items
And the menu content, top to bottom, is: a header (the name in semibold, and the email below
it in muted 12 px on desktop; on mobile a 36 px initials avatar, the name at 15 px semibold
and the email at 14 px muted), a "Profile" item (icon circle-user, highlighted with
--ui-bg-elevated while the route is /profile), a separator, the three checkbox items
"System", "Light" and "Dark" bound to useColorMode().preference with the current one
checked (kept from the shipped menu), a separator, and "Log out" (icon log-out); items are
32 px on desktop and 48 px at 15 px text on mobile
And activating "Profile" navigates to /profile and closes the menu (when already on /profile
it only closes); activating a theme item sets the preference and, in the desktop popover, keeps the menu open (the mobile sheet closes);
activating "Log out" behaves as today: POST /v1/auth/logout in a try/finally, then
session.clear() and a navigation to /login
And avatar initials are the uppercased first Unicode character of each of the first two words
of the display name; a display name with a single word, and a username, give their first two
characters, uppercased
And in the collapsed sidebar rail the chip shows only the avatar, keeps its accessible name
"{name} — account menu" and opens the same menu
And this slice does not touch the invitation or accept-invite work, does not change the
Users page, and does not add a way to change the username, email or password inside the page
Scenario Outline: Route guards for /profile
Given the session is <session>
When the user navigates to /profile
Then <outcome>
Examples:
| session | outcome |
| resolved, verified | ProfilePage renders |
| resolved, unverified | the app redirects to /register/pending |
| resolved with no session (401 from /auth/me) | the app redirects to /login?redirect=/profile&reason=expired |
Scenario: Default — the usual first visit with no display name
Given the session is verified with id 1, username "marta", email "marta@renew.example" and no
display name
When the user navigates to /profile
Then the breadcrumb reads "Profile" (mobile title "Profile")
And the Display name field is empty, shows the placeholder "e.g. Marta Alves", and the counter
reads "0 / 60"
And the footer reads "You appear as “marta”, your username."
And Save is disabled
And the Username input shows "marta" and the Email input shows "marta@renew.example", both
disabled
And the Password card text reads "To change it, we'll email a reset link to
marta@renew.example. The link works once, within 1 hour."
And the button reads "Send reset link", no note is shown, and no request other than the
session's was sent
Scenario: Loading — opened by URL before /auth/me has returned
Given GET /v1/auth/me has not yet resolved
When the user opens /profile directly by URL
Then the breadcrumb reads "Profile", and the page title and subtitle are shown
And three skeleton cards replace the real cards (one with a title bar and one input, one with a
title bar and two inputs, one with a title bar and one input), 16 px apart, in an
aria-busy="true" container
And AppBoot is not shown
When GET /v1/auth/me then resolves 200 for the verified user "marta"
Then the skeleton cards are replaced by the Default state
Scenario: Opened from the menu, the cached user renders at once
Given the user is on /home with a resolved session for "marta"
When the user activates "Profile" in the account menu
Then the Default state renders with no skeleton, and GET /v1/auth/me is not called again
Scenario: Editing — typing turns Save on
Given the user is on /profile in the Default state
When the user types "Marta Alves" into Display name
Then the counter reads "11 / 60" and the footer reads "Unsaved changes" in the warning color
And Save is enabled
And no request has been sent
Scenario Outline: The counter counts Unicode characters after trimming
Given the user is on /profile in the Default state
When the user types <value> into Display name
Then the counter reads "<count> / 60"
And the counter is <color> and Save is <save>
Examples:
| value | count | color | save |
| "Marta Alves" | 11 | muted | enabled |
| " Marta Alves " | 11 | muted | enabled |
| 60 repetitions of "a" | 60 | muted | enabled |
| 61 repetitions of "a" | 61 | red | disabled |
| 60 repetitions of "😀" | 60 | muted | enabled |
| 61 repetitions of "😀" | 61 | red | disabled |
| "Cafe" followed by U+0301 | 5 | muted | enabled |
| 5 spaces, 60 "a", 5 spaces | 60 | muted | enabled |
Scenario: Too long — over 60 characters shows a field error and keeps Save off
Given the user is on /profile in the Default state
When the user types "Marta Alves, Head of Renovations, Brussels and Wallonia office"
Then the counter reads "62 / 60" in the error color
And the help row shows the error "Use 60 characters or fewer." with the circle-alert icon
And the field has the error border
And the footer reads "Unsaved changes" in the warning color
And Save is disabled
When the user presses Enter in the field
Then PATCH /v1/user/me is never sent
When the user shortens the value to "Marta Alves"
Then the error disappears, the counter reads "11 / 60" and Save is enabled
Scenario Outline: Dirty is measured on the trimmed draft against the saved name
Given the session's display name is "<saved>"
When the user sets Display name to <typed>, read literally as described in the column
Then Save is <save>
And the footer reads "<footer>"
Examples:
| saved | typed | save | footer |
| | 3 spaces | disabled | You appear as “marta”, your username. |
| Marta Alves | Marta Alves | disabled | You appear as “Marta Alves”. |
| Marta Alves | Marta Alves and a space | disabled | You appear as “Marta Alves”. |
| Marta Alves | nothing | enabled | Unsaved changes |
| Marta Alves | Marta, 2 spaces, Alves | enabled | Unsaved changes |
Scenario: Enter saves when Save is enabled
Given the user is on /profile and has typed "Marta Alves"
When the user presses Enter in the field
Then PATCH /v1/user/me is sent once with JSON {"display_name": "Marta Alves"}
Scenario: Saving — the field is disabled and a second submit is ignored
Given the user is on /profile and has typed " Marta Alves " and PATCH /v1/user/me has not
resolved
When the user activates Save
Then PATCH /v1/user/me is sent with JSON {"display_name": "Marta Alves"}
And the field is disabled and dimmed, and the button reads "Saving…" with a loader-circle icon
When the user presses Enter or activates Save again
Then no second request is sent
Scenario: Saved — a 200 updates the session, the chip, the menu, the footer and raises a toast
Given the user is on /profile and Save has been activated with "Marta Alves"
When PATCH /v1/user/me resolves 200 with id 1, username "marta" and display_name "Marta Alves"
Then session.displayName is "Marta Alves"
And the sidebar chip reads "Marta Alves" with initials "MA"
And the field shows "Marta Alves" and is enabled, the counter reads "11 / 60"
And the footer reads "You appear as “Marta Alves”." and Save is disabled
And a toast appears: color success, icon i-lucide-circle-check, id "display-name-saved", title
"Display name saved", description "You now appear as Marta Alves across RenewCMS and in
emails."
And no leave-page confirmation opens when the user then navigates away
Scenario: The server's value wins over what was typed
Given the user has typed " Marta Alves " and activated Save
When PATCH /v1/user/me resolves 200 with display_name "Marta Alves"
Then the field, the chip and the toast all use "Marta Alves"
Scenario: Clearing the display name goes back to the username
Given the session's display name is "Marta Alves" and the username is "marta"
When the user empties Display name and activates Save
Then PATCH /v1/user/me is sent with JSON {"display_name": ""}
And when it resolves 200 with display_name "" the sidebar chip reads "marta" with initials "MA"
And the footer reads "You appear as “marta”, your username."
And a toast appears: color success, icon i-lucide-circle-check, id "display-name-saved", title
"Display name removed", description "You now appear as marta, your username."
Scenario Outline: Save failed — a 500 or a network failure keeps the text and offers a retry
Given the user is on /profile and Save has been activated with "Marta Alves"
When PATCH /v1/user/me <failure>
Then an error alert (role="alert", icon circle-x) in the Display name card reads "Couldn't save
your display name. Your text is still here. Try again in a moment."
And the field still shows "Marta Alves" and is enabled
And the footer reads "Unsaved changes" and Save is enabled
And session.displayName is unchanged and no toast is raised
When the user activates Save again
Then the alert disappears while the request is in flight
And PATCH /v1/user/me is sent again with the same body
Examples:
| failure |
| resolves with a 500 response |
| never reaches the server |
Scenario Outline: A 400 from the API
Given the user is on /profile and Save has been activated with "Marta Alves"
When PATCH /v1/user/me resolves 400 with body "<body>"
Then <effect>
Examples:
| body | effect |
| Display name must be 60 characters or fewer. | the field shows the error "Use 60 characters or fewer." and Save is disabled |
| invalid request body | the Save failed alert is shown and the text is kept |
Scenario: Leaving with unsaved changes asks for confirmation
Given the user is on /profile with the draft "Marta Alves" (dirty)
When the user activates "Users" in the navigation
Then a ConfirmDialog (neutral tone) opens, titled "Leave without saving?" with the text "Your
display name change hasn't been saved."
And its actions are "Discard changes" and "Keep editing"
When the user activates "Keep editing"
Then the dialog closes and the app stays on /profile with the draft intact
When the user tries to leave again and activates "Discard changes"
Then the app navigates to /users
And the display name saved in the session is unchanged
Scenario: No confirmation when nothing is unsaved
Given the user is on /profile in the Default state
When the user activates "Users" in the navigation
Then the app navigates to /users with no dialog
Scenario: A 401 while saving redirects without the leave dialog
Given the user is on /profile with the draft "Marta Alves"
When PATCH /v1/user/me resolves 401
Then the app redirects to /login?redirect=/profile&reason=expired
And no leave-page dialog opens
Scenario: Account menu — opened on desktop
Given the user is on /home on desktop with the session "marta", email "marta@renew.example",
no display name
When the user activates the account chip
Then the chip has aria-expanded="true" and the sand fill with ink text
And a 224 px popover opens above the chip, aligned to its left edge
And its header shows "marta" in semibold and "marta@renew.example" in muted 12 px
And below it are "Profile" (circle-user), a separator, "System", "Light", "Dark" (the
current preference checked), a separator, and "Log out" (log-out)
And every item is 32 px high
And "Profile" is not highlighted
And "System", "Light" and "Dark" form one group where choosing one applies the theme at once
and keeps the menu open
Scenario: Account menu — opened from the drawer on mobile
Given the user is on /home on a viewport below lg and the navigation drawer is open
When the user activates the account row in the drawer
Then the drawer closes and a bottom sheet with a grab handle opens over the --rc-overlay scrim,
with the Home page behind it
And its header shows a 36 px avatar "MA", the name "marta" at 15 px semibold and the email
"marta@renew.example" muted
And its items are 48 px high at 15 px text: "Profile", a separator, "System", "Light", "Dark",
a separator, "Log out"
And the sheet has the same items in the same order as the desktop popover, so it is no taller
than the board's sheet
Scenario: Account menu matches the board with no visual exception
Given web/visual/states.ts has no exception on the profile state "Account menu"
When `task visual:check -- profile "Account menu"` runs at desktop and mobile, light and dark
Then every capture is within 10 %
And System, Light and Dark are present in the popover and in the sheet
And item heights are 32 px on desktop and 48 px on mobile
Scenario Outline: Closing the menu
Given the account menu is open
When <action>
Then the menu closes, the chip has aria-expanded="false", and focus is on the chip
Examples:
| action |
| the user presses Escape |
| the user clicks outside the menu |
Scenario: Menu items
Given the account menu is open on /home
When the user activates "Profile"
Then the app navigates to /profile and the menu closes
Given the account menu is open on /profile
Then "Profile" is highlighted with --ui-bg-elevated
When the user activates "Profile"
Then the menu closes and the app stays on /profile with no new request
When the user opens the menu and activates "Log out"
Then POST /v1/auth/logout is sent, then the session is cleared and the app navigates to /login
Scenario: The chip is sand while on /profile even with the menu closed
Given the user is on /profile with the menu closed
Then the chip has the --rc-sand fill and #111111 text, and aria-expanded="false"
When the user navigates to /home
Then the chip has a transparent fill
Scenario: Theme choice stays in the menu
Given the account menu is open and useColorMode().preference is "system"
When the user activates "Dark"
Then useColorMode().preference is "dark"
And the menu closes
And reopening it shows "Dark" checked and "System" not checked
Scenario Outline: Avatar initials
Given the session has username "<username>" and display name "<display>"
Then the chip and the menu header show the initials "<initials>" and the name "<shown>"
Examples:
| username | display | initials | shown |
| marta | | MA | marta |
| marta | Marta Alves | MA | Marta Alves |
| marta | Marta Alves Costa | MA | Marta Alves Costa |
| ines | Inès Duarte | ID | Inès Duarte |
| elodie | Élodie Martin | ÉM | Élodie Martin |
| marta | Marta | MA | Marta |
| m.alves | | M. | m.alves |
Scenario: The collapsed rail keeps the menu and an accessible name
Given the sidebar is collapsed to its icon rail and the display name is "Marta Alves"
Then the chip shows only the avatar "MA" and has the accessible name "Marta Alves — account menu"
When the user activates it
Then the same menu opens
Scenario Outline: The Home greeting uses the display name, else the username
Given the session has username "marta" and display name "<display>"
When the user views /home at a local hour of 9
Then the greeting's name is "<name>"
Examples:
| display | name |
| | marta |
| Marta Alves | Marta Alves |
Scenario: A saved display name appears on Home without a reload
Given the user saved the display name "Marta Alves" on /profile
When the user navigates to /home
Then the greeting's name is "Marta Alves" and the chip reads "Marta Alves"
Scenario: Reset: sending — no confirmation, the button is busy
Given the user is on /profile with the session's display name "Marta Alves"
When the user activates "Send reset link"
Then POST /v1/auth/password-reset is sent with JSON {"email": "marta@renew.example"}
And the button reads "Sending…" with a loader-circle icon and is disabled
And no note is shown, and the sidebar chip still reads "Marta Alves"
Scenario: Reset: sent — the note stays and "Send again" sends a new link
Given "Send reset link" has been activated
When POST /v1/auth/password-reset resolves 200
Then the button reads "Send again" with the mail icon and is enabled
And a success note (role="status", icon mail-check) shows the title "Reset link sent" and the
text "Check marta@renew.example. The link works once, within 1 hour."
When the user activates "Send again"
Then POST /v1/auth/password-reset is sent again with the same body
And the note is hidden while it is in flight
When it resolves 200
Then the "Reset link sent" note is shown again
When the user navigates away and back to /profile
Then the button reads "Send reset link" and no note is shown
Scenario Outline: Reset: too many requests — the button is disabled for the Retry-After window
Given "Send reset link" has been activated
When POST /v1/auth/password-reset resolves 429 with <header>
Then a warning note (role="status", icon clock-alert) shows the title "Too many requests" and
the text "You've asked for several links recently. Wait a few minutes, then try again."
And the button reads "Send reset link", is disabled and is at 40 % opacity
When <seconds> seconds elapse
Then the button is enabled and the warning note is gone
Examples:
| header | seconds |
| a Retry-After of 42 | 42 |
| a Retry-After of 300 | 300 |
| no Retry-After header | 300 |
| a Retry-After of "soon" | 300 |
| a Retry-After of 0 | 300 |
Scenario Outline: Reset: failed — a 500 or a network failure leaves the button pressable
Given "Send reset link" has been activated
When POST /v1/auth/password-reset <failure>
Then an error note (role="status", icon circle-x) shows the title "Couldn't send the link" and
the text "Check your connection and try again."
And the button reads "Send reset link" and is enabled
When the user activates it and POST /v1/auth/password-reset resolves 200
Then the note becomes "Reset link sent" and the button reads "Send again"
Examples:
| failure |
| resolves with a 500 response |
| never reaches the server |
Scenario: Display names in the Users list
Given the session is "marta" with display name "Marta Alves"
And GET /v1/user/ resolves 200 with the 5-item Default fixture of users_screen.feature, where
user id 1 "marta" has display_name "Marta Alves" and user id 3 "ines" has display_name
"Inès Duarte"
When the user navigates to /users
Then the breadcrumb reads "Users" (mobile title "Users") and the sidebar chip reads "Marta Alves"
And the "marta" row shows "Marta Alves" with "marta" beside it in muted text and the "you" tag
and an Accepted badge
And the "ines" row shows "Inès Duarte" with "ines" beside it
And the "jonas" row shows "jonas" alone
+169
View File
@@ -0,0 +1,169 @@
# QA: Profile page, display name and the account menu
## Implementation note for coder (informational, not a QA assertion)
There is no Go change and no HTTP-level Go section: PATCH /v1/user/me, GET /v1/auth/me and POST
/v1/auth/password-reset are already covered (features/user_display_name.qa.md,
features/get_current_user.qa.md, features/request_password_reset.qa.md).
Amended specs (their Vitest tests must be updated in the same change): dashboard_shell_branding.feature
(UserMenu label, initials, groups and the collapsed aria-label), home.feature (greeting name),
plus session.spec.ts, useApi.spec.ts (getMe maps email and display_name, absent means ""),
UserMenu.spec.ts, DashboardShell.spec.ts and the HomeView spec.
The Saved toast uses `useToast().add({ id: 'display-name-saved', color: 'success', icon:
'i-lucide-circle-check', title: 'Display name saved', description: 'You now appear as {name}
across RenewCMS and in emails.' })`. The 429 countdown reuses `useRetryAfter`; the 300 s fallback
applies when `ApiError.retryAfter` is undefined or 0.
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi`'s `request` and `getMe` per case; no real backend. Mount ProfilePage inside
DashboardShell with a resolved verified session (id 1, username "marta", email
"marta@renew.example", displayName "") and a test router at /profile. Use fake timers only for the
countdown. No test freezes the system date; the Home greeting cases mock the hour as
home.qa.md does and assert the name part only. Run the layout cases at a desktop and a
below-lg width (mock `matchMedia`).
1. **Route guards, Examples-driven** - verified renders; unverified redirects to
/register/pending; 401 redirects to /login?redirect=/profile&reason=expired.
2. **Default** - breadcrumb "Profile", title, subtitle, empty field with placeholder, "0 / 60",
footer "You appear as “marta”, your username.", Save disabled, Username and Email inputs
disabled with their values, Password text with the email, "Send reset link", no note; no
nav item has aria-current.
3. **Loading** - unresolved GET /v1/auth/me; assert three skeleton cards, aria-busy, no AppBoot;
resolve and assert Default.
4. **From the menu** - navigate from /home via "Profile"; assert no skeleton and no second
GET /v1/auth/me.
5. **Editing** - type "Marta Alves"; assert "11 / 60", "Unsaved changes", Save enabled, no request.
6. **Counter, Examples-driven** - each table row, including the 60/61 emoji rows and "Cafe" +
U+0301 (5); assert count, color class and Save state.
7. **Too long** - the 62-character value; assert "62 / 60", the error with circle-alert, "Unsaved
changes", Save disabled, Enter sends nothing; shorten and assert the error clears.
8. **Dirty rules, Examples-driven** - each row.
9. **Enter saves** - assert one PATCH with body `{"display_name":"Marta Alves"}`.
10. **Saving** - unresolved PATCH with a padded value; assert the trimmed body, disabled and dimmed
field, "Saving…", and that Enter and a second click send nothing.
11. **Saved** - resolve 200; assert session.displayName, chip "Marta Alves" with "MA", field value,
"11 / 60", footer, Save disabled, the toast arguments, and no leave dialog after navigating.
12. **Server value wins** - resolve with a trimmed display_name; assert all consumers use it.
13. **Clearing** - saved "Marta Alves", empty the field, save; assert body `{"display_name":""}`,
chip "marta", footer, and the "Display name removed" toast.
14. **Save failed, Examples-driven** - `ApiError(500)` and `NetworkError`; assert the alert copy,
the kept value, the "Unsaved changes" footer, Save enabled, the session unchanged and no toast;
save again and assert the alert clears during the request and PATCH is sent again.
15. **400, Examples-driven** - `ApiError(400)` with the display-name text gives the field error;
with another body gives the Save failed alert.
16. **Leave guard** - dirty draft, navigate to /users; assert ConfirmDialog props (title, text,
"Keep editing" as confirm and "Discard changes" as cancel, neutral tone); Keep editing stays;
Discard leaves and leaves the session name unchanged. Also assert: clean draft leaves with no
dialog; a 401 during PATCH redirects with no dialog (authRedirectPending); Log out while dirty
shows the dialog.
17. **Menu, desktop** - click the chip; assert aria-haspopup, aria-expanded, title "Account", the
sand class, the header name and email, the item order (Profile, System, Light, Dark, Log out)
with the two separators, and Profile not highlighted.
18. **Menu, mobile** - below lg, open the drawer and activate the account row; assert the drawer
closed, the sheet with its grab handle, the 36 px avatar header and the same item order.
19. **Closing** - Escape and an outside click; assert closed, aria-expanded false, focus on the
chip; ArrowDown and ArrowUp move between items.
20. **Menu items** - Profile navigates and closes; on /profile it is highlighted, closes with no
navigation; Log out calls POST /v1/auth/logout, clears the session and goes to /login.
21. **Chip fill** - sand on /profile with the menu closed; not sand on /home.
22. **Theme** - activating "Dark" sets `useColorMode().preference`, closes the menu, and reopening
shows "Dark" checked.
23. **Initials, Examples-driven** - each row, including "Élodie Martin" giving "ÉM", a single
word giving two letters, and username "m.alves" giving "M." (first two characters).
24. **Collapsed rail** - avatar only, aria-label "Marta Alves — account menu", same menu.
25. **Home greeting, Examples-driven** - no display name gives "marta"; "Marta Alves" gives
"Marta Alves"; then save on /profile and navigate to /home and assert the new name. Do not
assert the greeting word or the hour.
26. **Reset: sending** - unresolved POST; assert body `{"email":"marta@renew.example"}`, "Sending…",
disabled, no note.
27. **Reset: sent and Send again** - 200 gives "Send again" and the mail-check note with the exact
copy; "Send again" hides the note during the request, sends the same body, and on 200 shows it
again; remounting resets to idle.
28. **Reset: 429, Examples-driven** - reject with `ApiError(429, <retryAfter>)`; assert the warning
note copy, disabled button reading "Send reset link"; advance fake timers by the table's
seconds minus 1 and assert still disabled, then by 1 and assert enabled with the note gone.
Rows: 42, 300, undefined (300), 0 (300).
29. **Reset: failed, Examples-driven** - `ApiError(500)` and `NetworkError`; assert the error note
copy, enabled button, and that a retry resolving 200 gives the sent note.
30. **Users list** - mount UsersPage with session display name "Marta Alves" and the users_screen
Default items where marta and ines carry display names; assert the marta row shows
"Marta Alves" then "marta" and the "you" tag, ines shows "Inès Duarte" then "ines", jonas
shows alone, and the chip reads "Marta Alves".
## Visual (task visual:check -- profile, and -- home; desktop and mobile, light and dark)
Reference: `docs/design/screens/profile.md`, board group "Profile" in `docs/design/source/RenewCMS
Screens Back-office.dc.html`, exact values in `docs/design/source/AppFrame.dc.html`. Add each
state's setup to `web/visual/states.ts` with the board's own sample data. The gate is hard: every
capture must be within 10 %. Base session mock: GET /v1/auth/me 200 with id 1, username
"marta", email "marta@renew.example", is_verified true, display_name "" (state-specific
overrides below).
- [ ] Account menu: /home with `now: boardNow` and the home Default fixtures, session as above
(id 1, "marta", "marta@renew.example", display_name ""), menu opened by clicking the chip
(on mobile: open the drawer, then the account row). Name "marta", initials "MA", email
"marta@renew.example". The board now draws System, Light and Dark, with Light checked in
its sample. The `exception` block is removed from web/visual/states.ts, so the default 10 %
gate applies. `task visual:check -- profile "Account menu"` must PASS on all four captures
(desktop and mobile, light and dark). If the only remaining diff is the board's Profile
highlight on Home (the app highlights Profile only on /profile), do NOT re-add an exception
and do NOT highlight Profile on Home. Stop and ask the user.
- [ ] Manual: item heights measured 32 px (desktop popover) and 48 px (mobile sheet); arrow keys move
between items; Escape and outside click close; choosing a theme keeps the menu open.
- [ ] Loading: /profile with GET /v1/auth/me hanging; three skeleton cards, 16 px apart.
- [ ] Default, no display name: empty field, "0 / 60", the username footer, Save at 40 %.
- [ ] Editing: type "Marta Alves"; field focused; "11 / 60"; "Unsaved changes"; Save enabled.
- [ ] Too long: type "Marta Alves, Head of Renovations, Brussels and Wallonia office"; "62 / 60"
red; error "Use 60 characters or fewer."; Save at 40 %.
- [ ] Saving: type "Marta Alves", press Save with PATCH hanging; disabled dimmed field, "Saving…".
- [ ] Saved: PATCH 200 with display_name "Marta Alves"; chip "Marta Alves" "MA"; toast "Display name
saved" / "You now appear as Marta Alves across RenewCMS and in emails."
- [ ] Save failed: PATCH 500 after typing "Marta Alves"; the error alert in the card; "Unsaved changes".
- [ ] Reset: sending: session display_name "Marta Alves"; POST /v1/auth/password-reset hanging;
"Sending…".
- [ ] Reset: sent: same session; POST 200; "Send again" and the "Reset link sent" note.
- [ ] Reset: too many requests (429): POST 429 with header `Retry-After: 300`; disabled button at
40 % and the "Too many requests" note.
- [ ] Reset: failed: POST 500; the "Couldn't send the link" note.
- [ ] Display names in the Users list: /users, session display_name "Marta Alves"; GET /v1/user/
with the five board rows (sam.oliveira@renew.example pending 27 Sep 2026, p.huber@gmail.com
expired 3 Aug 2026, ines "Inès Duarte" 18 Jun 2026, jonas 2 Apr 2026, marta "Marta Alves"
12 Mar 2026 with "you"). Clock-sensitive rendering is skipped per repo rules.
- [ ] `task visual:check -- home` still PASSes for Default, Loading, Empty and Error. The session
fixture has display_name "", so the greeting name is "marta". Extend the fixture with
`email` and `display_name` (it must tolerate them being absent).
- [ ] Layout from the board frame, not components.md: content column 720 px max; cards separated by
20 px; the footer strip has the status text left and Save right (32 px high on desktop, 44 px
on mobile); the account inputs are two columns on desktop and stacked on mobile; the
password input and button are a row (button aligned to the bottom edge) on desktop and
stacked, full width, on mobile.
- [ ] Not covered by screenshots: keyboard and focus order (Tab reaches the field, Save, "Send
reset link"; Escape returns focus to the chip; focus returns to the field after a failed
save), hover and active states, motion (popover and sheet, skeleton pulse 1.6 s, both
stopped under reduced motion).
- [ ] Not drawn, no visual state: the leave-page dialog, the "Display name removed" toast, the
400 variants. Vitest only (cases 13, 15, 16).
## Manual verification
- **Real round trips against `task dev`.** Vitest only mocks `useApi`. Save a display name and
confirm the chip, menu, Home greeting and Users list show it after a reload; clear it and
confirm the username returns; confirm login still works only with the username.
- **Unicode limit.** Paste 60 and 61 emoji and a combining-mark name; the client counter and
the API (`utf8.RuneCountInString`) agree at the boundary.
- **Real reset email** (needs real or sandboxed SMTP, `SMTP_HOST` and related vars). "Send reset
link" delivers a mail to the account's own address, the link ends on the reset-confirm screen,
and a completed reset invalidates the current session (`token_version`). "Send again"
invalidates the older link.
- **Real 429.** Exceed `AUTH_RATE_LIMIT_MAX_ATTEMPTS` within `AUTH_RATE_LIMIT_WINDOW_SECONDS` and
confirm the button re-enables when the real Retry-After elapses. The limiter budget is shared
with login.
- **API quirk, out of scope.** POST /v1/auth/password-reset returns 200 even if the mail cannot be
sent (the handler discards the use-case error), so with SMTP down the page still shows "Reset
link sent". Reported, not fixed here.
- **Mobile sheet and toasts on a real device.** The drawer-to-sheet handoff, scrim, safe-area
padding, and the toast placement (bottom center on mobile).
- **Theme persistence.** The choice made from the menu survives a reload.
+99
View File
@@ -0,0 +1,99 @@
Feature: Removing an image from an article
As an authenticated RenewCMS user managing the CMS
I want to delete an already-uploaded image by its id
So that a removed image's file and row are actually gone, and a delete on
an unknown article or an unknown image answers 404 the same way every
other article write does
Background:
Given internal/infrastructure/useCases.DeleteImageUseCase.DeleteImage(imageId)
already exists and calls image.Repository.Delete(imageId), which returns
image.ErrImageNotFound for an unknown id and, on the real ImageRepository,
also removes the uploaded file from UPLOAD_DIR, per
features/delete_article_cascades_images.feature
And this slice changes POST /v1/article/{id}/image's success response
(api/handlers/image.Handler.PostImage, features/upload_article_image.feature)
to also return the created image's numeric id, so the 201 body becomes
{"id": ..., "location": ...}; this lets a client address the image later
through this slice's DELETE route
And this slice mounts DELETE /v1/article/{articleId}/image/{imageId} in
api/router.go, in the same jwtauth Verifier + Authenticator group as
POST .../image
And this slice adds a DeleteImage method to api/handlers/image.Handler,
grows NewHandler's signature to also take DeleteImageUseCase, and wires
it in api/router.go
And DeleteImage parses articleId and imageId from the URL, answering 400
with apperr.IdUint32ErrorMessage if either isn't a valid uint32
And DeleteImage first calls GetArticleUseCase.GetArticle(articleId);
errors.Is(err, article.ErrArticleNotFound) answers 404 with
apperr.ArticleNotFoundErrorMessage; this only confirms the article id
in the URL names a real article, and does not verify that the image id
belongs to that article's Images slice (a shallow existence check on
both ids, not an ownership check)
And DeleteImage then calls DeleteImageUseCase.DeleteImage(imageId);
errors.Is(err, image.ErrImageNotFound) answers 404 with the new
apperr.ImageNotFoundErrorMessage = "Image not found"; any other error
falls back to the existing generic 500
And on success DeleteImage answers 204 with an empty body, the same shape
as DELETE /v1/article/{id}
Scenario: Removing an image from an article it belongs to succeeds
Given a valid jwt cookie for a user with id 1
And the article repository contains an article with id 1 titled
"Backyard Renovation Update" whose Images slice holds image id 10
And the image repository contains an image with id 10
When the client sends DELETE /v1/article/1/image/10 with that cookie
Then the response status is 204
And the response body is empty
And the image repository no longer contains an image with id 10
Scenario: Removing an image from an unknown article answers 404 and never touches the image repository
Given a valid jwt cookie for a user with id 1
And the article repository has no article with id 9999
And the image repository contains an image with id 10
When the client sends DELETE /v1/article/9999/image/10 with that cookie
Then the response status is 404
And the response body is the text "Article not found"
And the image repository's Delete is never called
And the image repository still contains the image with id 10
Scenario: Removing an unknown image from an existing article answers 404
Given a valid jwt cookie for a user with id 1
And the article repository contains an article with id 1 titled
"Backyard Renovation Update"
And the image repository has no image with id 9999
When the client sends DELETE /v1/article/1/image/9999 with that cookie
Then the response status is 404
And the response body is the text "Image not found"
Scenario: Removing an image id that belongs to a different article still succeeds, because the check is shallow
Given a valid jwt cookie for a user with id 1
And the article repository contains an article with id 1 titled
"Backyard Renovation Update" whose Images slice is empty
And the article repository contains a second article with id 2 whose
Images slice holds image id 10
And the image repository contains an image with id 10
When the client sends DELETE /v1/article/1/image/10 with that cookie
Then the response status is 204
And the image repository no longer contains an image with id 10
Scenario: Removing an image still requires authentication
Given no jwt cookie is sent
And the article repository contains an article with id 1 titled
"Backyard Renovation Update" whose Images slice holds image id 10
And the image repository contains an image with id 10
When the client sends DELETE /v1/article/1/image/10 without a cookie
Then the response status is 401
And the image repository still contains the image with id 10
Scenario Outline: A malformed id in the URL answers 400 before either repository is touched
Given a valid jwt cookie for a user with id 1
When the client sends DELETE /v1/article/<article_id>/image/<image_id> with that cookie
Then the response status is 400
And the response body is the text "The server expects the ID to be in the format of an unsigned 32-bit integer (uint32)."
Examples:
| article_id | image_id |
| abc | 10 |
| 1 | abc |
+56
View File
@@ -0,0 +1,56 @@
# QA procedure: remove_article_image
Package: `test` (black-box, extending `article_test.go` / `image_test.go`).
## Setup shared by every case
1. Call `validator.InitValidator()` once.
2. Reuse `mockArticleRepo` and `mockImageRepo` as-is.
3. Wire `useCases.NewDeleteImageUseCase(imageRepo)` (already used by
`delete_article_cascades_images.qa.md`'s suite) alongside the existing
use cases.
4. Build `image.NewHandler(...)` with its grown constructor including the
delete use case, matching whatever parameter order the coder settles on.
5. Build a test `jwtauth.New("HS256", []byte("test-secret"), nil)`.
6. Mount `DELETE /{id}/image/{imageId}` alongside the existing article
routes under the authenticated group, mirroring `api/router.go` after
this slice.
7. Mint a valid jwt cookie for user id 1 as in `upload_article_image.qa.md`.
## HTTP checks
8. Seed `articleRepo.articles[1]` with `Images: []*image.Image{{ID: 10}}`
and `imageRepo.images[10] = image.Image{ID: 10}`. Send
`DELETE /v1/article/1/image/10` with the valid cookie. Assert status
204, empty body; assert `imageRepo.images` no longer has key 10.
9. Empty `articleRepo`; seed `imageRepo.images[10]`. Send
`DELETE /v1/article/9999/image/10`. Assert 404, body
`"Article not found\n"`; assert `imageRepo.images` still has key 10
(Delete never called — track via a call-count field on the fake, the
same way the existing fakes already track `Create`).
10. Seed `articleRepo.articles[1]`; empty `imageRepo`. Send
`DELETE /v1/article/1/image/9999`. Assert 404, body
`"Image not found\n"`.
11. Seed `articleRepo.articles[1]` (empty Images) and `articleRepo.articles[2]`
with `Images: []*image.Image{{ID: 10}}`; seed `imageRepo.images[10]`.
Send `DELETE /v1/article/1/image/10`. Assert 204; assert
`imageRepo.images` no longer has key 10 — asserts the shallow-check
contract from the feature's fourth scenario.
12. Seed as in step 8. Send `DELETE /v1/article/1/image/10` with **no**
cookie. Assert 401; assert `imageRepo.images` still has key 10.
13. Examples-driven: send `DELETE /v1/article/abc/image/10` and
`DELETE /v1/article/1/image/abc` with the valid cookie. Assert 400,
body `"The server expects the ID to be in the format of an unsigned
32-bit integer (uint32).\n"` for each.
## Also touched by this slice: upload_article_image's 201 body
14. Extend `upload_article_image.qa.md`'s existing 201-body assertion to
also decode and check the `id` field equals the newly created image's
`ID` in `imageRepo.images`.
## Manual verification (not exercised by the Go test)
- Real DELETE against a real SQLite file and real UPLOAD_DIR: confirm the
file is actually removed from disk and the `article_images` join row is
gone, the same way `upload_article_image.qa.md`'s manual item covers the
POST side.
- SPA-visible behaviour: covered separately by
`features/editor_image_removal.qa.md`.
- No SMTP involvement.
+132
View File
@@ -0,0 +1,132 @@
Feature: Password reset confirm screen
As a user who opened the reset link from their email
I want /register/reset/validate?c=CODE&email=EMAIL to let me choose a new password via POST
/v1/auth/password-reset/confirm, checking length and match in the browser first, and to tell
me plainly when the link is incomplete, the code is wrong or expired, or the server failed
So that finishing a password reset is a single form from the email, with the same neutral
"invalid or expired" message whether the code was wrong, reused, or the account doesn't exist
Background:
Given /register/reset/validate is a public route (meta.auth "public") rendered as
ResetConfirmPage inside AuthShell, per docs/design/routes.md
And ResetConfirmPage only calls POST /v1/auth/password-reset/confirm
And on mount, ResetConfirmPage reads the "c" and "email" query parameters once: if either is
absent or an empty string, no request is ever made and the Missing parameters state renders
immediately instead of the form
And when both are present, the form has a read-only Email field (value from the "email" query
parameter, help text "From your reset link."), a New password field (password input with
show/hide, a live checklist item "At least 8 characters" that starts unmet/gray, turns
error/red only after a failed submit, and turns met/green once satisfied), and a Confirm new
password field (password input with show/hide, a live checklist item "Passwords match"
with the same unmet/error/met states)
And New password's length is checked on submit only: fewer than 8 characters leaves its
checklist item in its error state and blocks the request
And Confirm new password's match against New password is checked on blur of that field and
again on submit: a mismatch shows the error "The passwords don't match." and leaves the
"Passwords match" checklist item in its error state, and blocks the request
And a submit that passes both checks calls POST /v1/auth/password-reset/confirm with
{ email, code: c, password: <New password> }; the Confirm new password value is never sent
And on a 200 response, the app navigates to "/login?reason=password-changed", whose
rendering is covered by features/login_screen.feature's "Password changed" scenario, not
re-specified here
And a 403 response (per features/reset_password.feature, covering an unknown email, a wrong
code, an already-used code, or an expired code alike) replaces the whole form with a
ResultPanel
And a 500 response, or a request that never reaches the server, is surfaced with the app's
generic network/server-error alert — icon "i-lucide-circle-x", title "Couldn't reach
RenewCMS", description "Check your connection and try again.", the same copy LoginPage and
RegisterPage already use for the same failure; the form is not replaced, both password
fields keep whatever the user typed, and the form re-enables, since
docs/design/screens/reset-password.md has no state of its own for this response and this
is the app's generic pattern for it (per the user's decision on this slice)
Scenario: Default — both parameters present, an untouched form
When the user navigates to "/register/reset/validate?c=abc123&email=marta%40renew.example"
Then the heading is "Choose a new password"
And the description is "Pick something you haven't used here before. You'll log in with it
next."
And the Email field shows "marta@renew.example", read-only, with help "From your reset link."
And the New password field shows no value, with checklist item "At least 8 characters" in its
unmet state
And the Confirm new password field shows no value, with checklist item "Passwords match" in
its unmet state
And the submit button reads "Change password"
Scenario: Too short — fewer than 8 characters blocks submission
Given the user is on the reset-confirm form with New password "lime" and Confirm new
password "lime"
When the user submits
Then POST /v1/auth/password-reset/confirm is never called
And the New password checklist item "At least 8 characters" shows its error state
And the Confirm new password checklist item "Passwords match" shows its met state, since both
fields hold the same value
Scenario: Mismatch — caught on blur and on submit
Given the user is on the reset-confirm form with New password "limewash2026"
When the user types "limewash2025" into Confirm new password and blurs the field
Then the Confirm new password field shows the error "The passwords don't match." and its
checklist item "Passwords match" shows its error state
When the user submits with these same values
Then POST /v1/auth/password-reset/confirm is never called
And the same mismatch error is still shown
Scenario: Submitting — fields and button are disabled while the request is in flight
Given the user is on the reset-confirm form with New password "limewash2026" and Confirm new
password "limewash2026"
When the user submits and POST /v1/auth/password-reset/confirm has not yet resolved
Then the New password and Confirm new password fields are disabled
And the submit button reads "Changing password…" and shows a loading state
Scenario: Success — a 200 hands off to the log-in screen
Given the user is on "/register/reset/validate?c=abc123&email=marta%40renew.example" with
New password "limewash2026" and Confirm new password "limewash2026"
When the user submits and POST /v1/auth/password-reset/confirm resolves 200
Then the app navigates to "/login?reason=password-changed"
Scenario: Invalid or expired — a 403 replaces the form with a ResultPanel
Given the user is on "/register/reset/validate?c=abc123&email=marta%40renew.example" with
New password "limewash2026" and Confirm new password "limewash2026"
When the user submits and POST /v1/auth/password-reset/confirm resolves 403 with the
apperr.PasswordResetFailedErrorMessage body
Then the form is no longer shown
And a ResultPanel is shown with tone "error", icon "i-lucide-link-2-off", title "This reset
link has expired", text "Reset links work once, for 1 hour. Request a new one and use it
within the hour."
And its actions are a primary "Request a new link" and a secondary "Back to log in"
When the user activates "Request a new link"
Then the app navigates to /register/reset/request
When instead the user activates "Back to log in"
Then the app navigates to /login
Scenario Outline: Server or network error — the form keeps its values and re-enables
Given the user is on "/register/reset/validate?c=abc123&email=marta%40renew.example" with
New password "limewash2026" and Confirm new password "limewash2026"
When the user submits and POST /v1/auth/password-reset/confirm <failure>
Then an error alert reads "Couldn't reach RenewCMS" with description "Check your connection
and try again."
And the form is still shown, not replaced by a ResultPanel
And the New password field still shows "limewash2026" and the Confirm new password field
still shows "limewash2026", both re-enabled
And the submit button reads "Change password" again, no longer loading
Examples:
| failure |
| fails with a 500 response |
| never reaches the server |
Scenario Outline: Missing parameters — either missing parameter blocks the request
When the user navigates to <path>
Then no request is made
And a ResultPanel is shown with tone "error", icon "i-lucide-link-2-off", title "This link
is incomplete", text "Part of the reset link is missing. Open it from your email again, or
request a new one."
And its single action is a primary "Request a new link"
When the user activates "Request a new link"
Then the app navigates to /register/reset/request
Examples:
| path |
| "/register/reset/validate?email=marta%40renew.example" |
| "/register/reset/validate?c=abc123" |
| "/register/reset/validate" |
+83
View File
@@ -0,0 +1,83 @@
# QA: Password reset confirm screen
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi` (`POST /v1/auth/password-reset/confirm`) per case; no real backend, no httptest
server. Mount ResetConfirmPage inside AuthShell with a test router whose current route starts at
the query string each case needs.
1. **Default state** — mount at
"/register/reset/validate?c=abc123&email=marta%40renew.example"; assert heading "Choose a new
password", description, Email "marta@renew.example" read-only with help "From your reset
link.", New password empty with checklist "At least 8 characters" unmet, Confirm new password
empty with checklist "Passwords match" unmet, submit "Change password".
2. **Too short state** — from state 1, set New password and Confirm new password both to "lime";
submit; assert `POST /v1/auth/password-reset/confirm` was never called; assert "At least 8
characters" shows its error state and "Passwords match" shows its met state.
3. **Mismatch state** — from state 1, set New password to "limewash2026", type "limewash2025"
into Confirm new password and blur; assert the error "The passwords don't match." and the
"Passwords match" checklist error state; submit; assert the call was never made and the same
error is still shown.
4. **Submitting state** — from state 1, set both password fields to "limewash2026"; mock the call
with an unresolved promise; submit; assert both fields are disabled and the submit button
reads "Changing password…" with a loading indicator.
5. **Success state** — from state 1, set both password fields to "limewash2026"; mock the call
resolving 200; submit; assert the router's current path is "/login?reason=password-changed"
(the rendering of that page is covered by `login_screen.qa.md`, not re-asserted here beyond
the path/query).
6. **Invalid or expired state** — from state 1, set both password fields to "limewash2026"; mock
the call resolving 403 with the `apperr.PasswordResetFailedErrorMessage` body; submit; assert
the form is no longer rendered; assert a ResultPanel (error, link-2-off, "This reset link has
expired", the text above) with actions "Request a new link" (primary) and "Back to log in"
(secondary); click each in separate sub-cases and assert the router's current path is
/register/reset/request and /login respectively.
7. **Server or network error state** — two sub-cases (500 response, rejected fetch) from state 1,
with both password fields set to "limewash2026"; submit; assert an error alert with icon
"i-lucide-circle-x", title "Couldn't reach RenewCMS", description "Check your connection and
try again." (the same copy `login_screen.qa.md` and `register_screen.qa.md` already assert
for their own server/network cases); assert the form is still rendered (no ResultPanel);
assert both password fields still read "limewash2026" and are re-enabled; assert the submit
button reads "Change password" and is no longer loading.
8. **Missing parameters state** — three sub-cases, one per Examples row (missing "c", missing
"email", missing both); mount at the row's path; assert no request was made; assert a
ResultPanel (error, link-2-off, "This link is incomplete", the text above) with a single
primary action "Request a new link"; click it and assert the router's current path is
/register/reset/request.
| path |
|----------------------------------------------------------|
| /register/reset/validate?email=marta%40renew.example |
| /register/reset/validate?c=abc123 |
| /register/reset/validate |
## Visual (manual verification — desktop and mobile, light and dark)
Reference: `docs/design/source/RenewCMS Screens Auth.dc.html`, group "Reset password". Run
`task visual:check -- reset-password` for each state.
- [ ] Default state: read-only Email field styling, both checklist items in their unmet/gray
state, matches the board exactly.
- [ ] Too short state: New password's checklist item in its error/red state while Confirm new
password's stays met/green, since both fields match.
- [ ] Mismatch state: inline field error under Confirm new password plus its checklist error
state.
- [ ] Submitting state: disabled field styling and the loading spinner in the submit button.
- [ ] Invalid or expired state: ResultPanel with both actions, primary first (components.md's
safe/primary-on-top rule for stacked mobile buttons).
- [ ] Server or network error state: error alert (circle-x icon, no close button) above the
heading, matching Login's/Register's own server-error alert styling exactly, since this
screen has no board state of its own for it; fields retain their values. This state is not
covered by `task visual:check`'s per-state board comparison (no board frame exists for it);
note that gap in the run's report rather than skipping it silently.
- [ ] Missing parameters state: ResultPanel with a single primary action.
- [ ] Keyboard/focus: Tab order is New password → show/hide → Confirm new password → show/hide →
submit; the ResultPanel's title receives focus on both the Invalid-or-expired and
Missing-parameters states; the mismatch error and the server/network alert are announced
without stealing focus from the field or the heading, respectively.
## Manual verification
- **Real POST /v1/auth/password-reset/confirm against a running server** — Vitest only mocks
`useApi`; confirm the real 200/403 round-trip (including the actual bcrypt code check, 1-hour
expiry, and single-use clearing) against `task dev` with a live SQLite file. The endpoint's own
contract is already covered by `features/reset_password.qa.md`; this slice only re-verifies the
screen consumes it correctly.
+85
View File
@@ -0,0 +1,85 @@
Feature: Password reset request screen
As a RenewCMS user who forgot their password
I want a /register/reset/request screen that emails a reset link via POST
/v1/auth/password-reset, validates the email client-side before sending, and never reveals
whether the address has an account
So that I can ask for a reset link with the same neutral confirmation regardless of whether my
account exists, and see plainly when I'm asking too often or the server failed
Background:
Given /register/reset/request is a public route (meta.auth "public") rendered as
ResetRequestPage inside AuthShell, per docs/design/routes.md
And ResetRequestPage only calls POST /v1/auth/password-reset
And the form has a single Email field (placeholder "you@example.com")
And client-side validation runs on submit only, before any request is sent: Email must be a
well-formed email address (the same pattern RegisterPage already uses), and a failing Email
shows "Enter a full email address, like name@example.com."
And a valid submit calls POST /v1/auth/password-reset with { email }
And every response the API gives — whether the email belongs to an account or not — is the
same 200 with the same body, per features/request_password_reset.feature, so the screen
shows the same Sent state either way
And a 429 response carries a Retry-After header in seconds, surfaced by useApi and displayed
as a live countdown on the submit button, the same mechanism LoginPage's own 429 handling
uses, and the Email field is disabled for the same duration
And a 500 response, or a request that never reaches the server, is surfaced as a
server/network error; the field keeps whatever the user typed and the form re-enables
And a 400 response is not expected once client-side validation passes, since the client
checks the same required,email rule the API enforces; it is out of scope for this slice
Scenario: Default — a fresh, empty form
When the user navigates to /register/reset/request
Then the heading is "Reset your password"
And the description is "Enter the email for your account and we'll send you a link to choose
a new password."
And the Email field shows placeholder "you@example.com" with no value
And the submit button reads "Send reset link"
And the footer reads "Back to log in" linking to /login
Scenario: Validation error — an invalid email blocks the request
Given the user is on /register/reset/request
When the user types "marta@renew" into Email and submits
Then POST /v1/auth/password-reset is never called
And the Email field shows the error "Enter a full email address, like name@example.com."
Scenario: Submitting — the field and button are disabled while the request is in flight
Given the user is on /register/reset/request with Email "marta@renew.example"
When the user submits and POST /v1/auth/password-reset has not yet resolved
Then the Email field is disabled
And the submit button reads "Sending…" and shows a loading state
Scenario: Sent — any 200 shows the same neutral confirmation
Given the user is on /register/reset/request with Email "marta@renew.example"
When the user submits and POST /v1/auth/password-reset resolves 200
Then the form is replaced by a ResultPanel with tone "success", icon "i-lucide-mail-check",
title "Check your email", text "If an account exists for that email, a password reset link
has been sent.", and note "The link expires in 1 hour."
And its single action is a secondary "Back to log in"
When the user activates "Back to log in"
Then the app navigates to /login
Scenario: Too many attempts — the button is disabled with a live countdown
Given the user is on /register/reset/request with Email "marta@renew.example"
When the user submits and POST /v1/auth/password-reset resolves 429 with a Retry-After of 58
seconds
Then an info alert reads "Too many requests" with description "Wait a moment before asking
for another link."
And the Email field still shows "marta@renew.example"
And the submit button reads "Try again in 0:58" and is disabled
And the Email field is disabled while the countdown runs
When 58 seconds elapse
Then the submit button re-enables and reads "Send reset link"
And the Email field is editable again
Scenario Outline: Server or network error — the field keeps its value and re-enables
Given the user is on /register/reset/request with Email "marta@renew.example"
When the user submits and POST /v1/auth/password-reset <failure>
Then an error alert reads "Couldn't send the link" with description "Check your connection
and try again."
And the Email field still shows "marta@renew.example" and is re-enabled
And the submit button reads "Send reset link" again, no longer loading
Examples:
| failure |
| fails with a 500 response |
| never reaches the server |
+59
View File
@@ -0,0 +1,59 @@
# QA: Password reset request screen
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi` (`POST /v1/auth/password-reset`) per case; no real backend, no httptest server.
Mount ResetRequestPage inside AuthShell with a test router.
1. **Default state** — mount at /register/reset/request; assert heading "Reset your password",
description, Email placeholder "you@example.com" with no value, submit "Send reset link",
footer "Back to log in" linking to /login.
2. **Validation error state** — set Email to "marta@renew", submit; assert the mocked
`POST /v1/auth/password-reset` was never called; assert the error "Enter a full email
address, like name@example.com."
3. **Submitting state** — set Email "marta@renew.example"; mock the call with an unresolved
promise; submit; assert the Email field is disabled and the submit button reads "Sending…"
with a loading indicator.
4. **Sent state** — set Email "marta@renew.example"; mock the call resolving 200; submit; assert
the form is replaced by a ResultPanel (success, mail-check, "Check your email", the neutral
text, note "The link expires in 1 hour.") with a single secondary action "Back to log in";
click it and assert the router's current path is /login.
5. **Too many attempts state** — set Email "marta@renew.example"; mock the call resolving 429
with `Retry-After: 58`; submit; assert an info alert ("Too many requests", "Wait a moment
before asking for another link."); assert Email still reads "marta@renew.example"; assert the
submit button reads "Try again in 0:58" and is disabled; assert the Email field is disabled;
advance fake timers 58s; assert the button re-enables and reads "Send reset link" and the
field is editable again.
6. **Server or network error state** — two sub-cases (500 response, rejected fetch) with Email
"marta@renew.example"; submit; assert an error alert ("Couldn't send the link", "Check your
connection and try again."); assert Email still reads "marta@renew.example" and is re-enabled;
assert the submit button reads "Send reset link" and is no longer loading.
## Visual (manual verification — desktop and mobile, light and dark)
Reference: `docs/design/source/RenewCMS Screens Auth.dc.html`, group "Forgot password". Run
`task visual:check -- forgot-password` for each state.
- [ ] Default state: heading, description, Email field, "Send reset link" button, "Back to log
in" footer link, matches the board exactly.
- [ ] Validation error state: the inline field error renders with the same styling as
Register's/Login's own field errors.
- [ ] Submitting state: disabled field styling and the loading spinner in the submit button.
- [ ] Sent state: ResultPanel (mail-check icon) with its single secondary action, note text below
the description.
- [ ] Too many attempts state: info alert (timer icon), disabled field and disabled button with
the live "Try again in m:ss" countdown text.
- [ ] Server error state: error alert (circle-x icon, no close button), field retains its value.
- [ ] Keyboard/focus: Tab order is Email → submit; the alert (when present) is announced via
`role="status"` (info) or `role="alert"` (error) without re-announcing on re-render; the
ResultPanel's title receives focus on the Sent state.
## Manual verification
- **Real POST /v1/auth/password-reset against a running server** — Vitest only mocks `useApi`;
confirm the real 200/429/500 round-trip (including the actual rate limiter and Retry-After
header) against `task dev` with a live SQLite file. The endpoint's own contract is already
covered by `features/request_password_reset.qa.md`; this slice only re-verifies the screen
consumes it correctly.
- **429 countdown drift** — confirm `useRetryAfter`'s live countdown does not drift against a
real elapsed 58-second wait, since Vitest fake timers only prove the logic.
+131
View File
@@ -0,0 +1,131 @@
Feature: Settings page and GET /v1/settings
As a verified RenewCMS user in the shared workspace
I want a Settings page that shows the version of the RenewCMS build I am running
So that I can tell which build is deployed when I report a problem or check an upgrade
Background:
Given GET /v1/settings is mounted under /v1 in api/router.go in its own router, behind
jwtauth.Verifier, jwtauth.Authenticator, middleware.RequireCurrentToken and
middleware.RequireVerifiedUser, the same chain as NewUserRouter
And the response of a verified caller is 200 with the JSON body {"version": "<value>"}, one
snake_case field and nothing else, built from the domain entity settings.Settings in
internal/domain/settings
And GetSettingsUseCase (internal/infrastructure/useCases) is built with the version string and
depends only on the domain package; the handler in api/handlers/settings receives it
through NewHandler and never reads config, os or the environment
And config.Settings gains a Version field; cmd/server/main.go sets it from its own
main.version variable ("dev" unless set with -ldflags -X main.version) right after
config.NewSettingsFromEnv, and api/dependecyInjection.go passes settings.Version to the use
case; no os.Getenv or os.LookupEnv for the version appears outside cmd/server/main.go and
internal/infrastructure/config, and the version is captured once at startup
And /settings is a verified route (meta.auth "verified", meta.title "Settings") rendered as
SettingsPage inside DashboardShell, per docs/design/routes.md and docs/design/screens/settings.md
And SettingsPage calls GET /v1/settings once per navigation to it
And the PageHeader shows breadcrumb "Settings" (mobile title "Settings"), the page title
"Settings" and the subtitle "Workspace information."
And the page is at most 720 px wide, with padding 32 px on desktop and 20px 16px 88px on
mobile, and 20 px between the header and the card
And the page holds one card, --ui-bg with a 1 px --ui-border, 20 px padding on desktop and
16 px on mobile, containing a single row laid out as the board frame draws it: the label at
the left, the value at the right, vertically centred, 16 px apart
And the label is "Version" (15 px semibold, --ui-text-highlighted) and the value is the
server's version string in IBM Plex Mono 14 px, --ui-text-toned, with no "v" added by the
SPA
And the page has no action, toggle, link or input; every verified user sees it, owner and
admin alike
And DashboardShell's navigation gains "Settings" (icon settings, i-lucide-settings, linking to
/settings) after "Integration", in the sidebar and in the mobile drawer, so it lists five
destinations in this order: Home, Articles, Users, Integration, Settings
And skeleton placeholders show only after 150 ms of loading, so a fast response never flashes
them
And the Loading and Error states are not drawn in docs/design; they are decided in this spec
and covered by Vitest only (no visual state)
Scenario Outline: A verified caller gets the running build's version
Given the process was started with a config.Settings whose Version is "<version>"
And a verified user is logged in with a valid jwt cookie
When the client sends GET /v1/settings
Then the response status is 200
And the response body is exactly the JSON object {"version": "<version>"}
Examples:
| version |
| v2.2.0-beta |
| dev |
Scenario: The use case returns the version it was built with
Given GetSettingsUseCase is built with the version "v2.2.0-beta"
When GetSettings is called
Then it returns a settings.Settings whose Version is "v2.2.0-beta"
Scenario: A request without a jwt cookie is refused
When the client sends GET /v1/settings with no jwt cookie
Then the response status is 401
And the use case is not consulted for the response
Scenario: A token whose version no longer matches the account is refused
Given user id 7 exists with token version 1
And the jwt cookie was minted for user 7 with token version 0
When the client sends GET /v1/settings with that cookie
Then the response status is 401
And the response body is apperr.UnauthorizedErrorMessage
Scenario: An unverified account is refused
Given user id 8 exists with is_verified false and a valid jwt cookie
When the client sends GET /v1/settings with that cookie
Then the response status is 403
And the response body is apperr.VerificationRequiredErrorMessage
And the response does not contain the version
Scenario: Default — the Version row shows the server's version
Given GET /v1/settings resolves 200 with {"version": "v2.2.0-beta"}
When the user navigates to /settings
Then the breadcrumb reads "Settings" (mobile title "Settings")
And the header shows the title "Settings" and the subtitle "Workspace information."
And the card shows one row: the label "Version" and the value "v2.2.0-beta"
And the "Settings" nav item has aria-current="page" and no other nav item does
Scenario: The value is shown exactly as reported, with no prefix added
Given GET /v1/settings resolves 200 with {"version": "dev"}
When the user navigates to /settings
Then the value reads "dev"
Scenario: Navigation — "Settings" sits after Integration
Given the user is on /home
When DashboardShell mounts
Then the sidebar and the mobile drawer list Home, Articles, Users, Integration, Settings in
that order
And "Settings" has the settings icon and links to /settings
Scenario: Loading — the value becomes a skeleton after 150 ms while the request is in flight
Given GET /v1/settings has not yet resolved
When the user navigates to /settings
Then the label "Version" is visible at once, and nothing stands in for the value during the
first 150 ms
And after 150 ms a skeleton replaces the value only, and the card is aria-busy="true"
When GET /v1/settings then resolves 200 with {"version": "v2.2.0-beta"}
Then the skeleton is replaced by "v2.2.0-beta" and aria-busy is no longer set
Scenario Outline: Error — a 500 or a network failure replaces the row with an inline alert and a retry
Given GET /v1/settings <failure>
When the user navigates to /settings
Then the card shows an error alert with no close button and no title, reading "Couldn't reach
RenewCMS. Check your connection and try again.", with an action "Try again" (icon rotate-cw)
And the "Version" row is not shown
And the header (title and subtitle) is still shown
When the user activates "Try again"
Then the Loading state shows and GET /v1/settings is sent again
When it then resolves 200 with {"version": "v2.2.0-beta"}
Then the Default state's row replaces the alert
Examples:
| failure |
| resolves with a 500 response |
| never reaches the server |
Scenario: A 401 or an unverified 403 is handled globally, not by the page
Given GET /v1/settings resolves 401
When the user navigates to /settings
Then useApi's global handling redirects to "/login?redirect=/settings&reason=expired"
And SettingsPage shows no error alert of its own
+92
View File
@@ -0,0 +1,92 @@
# QA: Settings page and GET /v1/settings
## Automated Go (`task test`, package `test`, black-box)
Files: `test/settings_test.go` (use case) and `test/settings_http_test.go` (HTTP). Fakes: reuse
`mockUserRepo` from `test/user_test.go`; no settings repository exists, so none is needed. Name any
new fake uniquely, since all fakes share one package.
Setup shared by the HTTP cases:
1. Call `validator.InitValidator()` once.
2. Build `token := jwtauth.New("HS256", []byte("test-secret"), nil)`, `getUser :=
useCases.NewGetUserUseCase(userRepo)` and `settingsHandler :=
settings.NewHandler(useCases.NewGetSettingsUseCase(version))`.
3. Mount on a fresh `chi.NewRouter()` mirroring `NewSettingsRouter`:
`r.Route("/v1/settings", ...)` with `jwtauth.Verifier(token)`, `jwtauth.Authenticator(token)`,
`middleware.RequireCurrentToken(getUser)`, `middleware.RequireVerifiedUser(getUser)`, then
`r.Get("/", settingsHandler.GetSettings)`. No live server, no SQLite, no SMTP.
4. Mint cookies with `token.Encode(map[string]any{"user_id": uint32(id), "token_version":
uint32(v)})`, as in `test/stale_token_invalidation_http_test.go`.
Cases:
5. Use case, table-driven over versions "v2.2.0-beta" and "dev": `NewGetSettingsUseCase(v)
.GetSettings().Version == v`. The rule that `internal/domain/settings` and the use case do not
import `config`, `os`, `net/http` or `gorm` is a review item, not a Go test.
6. Verified user id 7 (`IsVerified: true`, `TokenVersion: 0`), matching cookie, version
"v2.2.0-beta": `GET /v1/settings` returns 200 and the body decodes to exactly one key
`version` equal to "v2.2.0-beta" (decode into `map[string]any` and assert `len == 1`). Repeat
with version "dev".
7. No cookie: 401. Do not assert an exact body (it is produced by `jwtauth.Authenticator`).
8. User 7 with `TokenVersion: 1`, cookie encoding `token_version: 0`: 401, body exactly
`apperr.UnauthorizedErrorMessage`.
9. User 8 with `IsVerified: false`, matching cookie: 403, body exactly
`apperr.VerificationRequiredErrorMessage`, and the body does not contain the version string.
10. After building the router, call `t.Setenv("ENVIRONMENT", "development")` and re-request as in
case 6: the response is unchanged (nothing is read from the environment at request time).
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi`'s `request` for `GET /v1/settings`. Mount SettingsPage inside DashboardShell with a
resolved verified session and a test router at /settings. Use fake timers for the 150 ms cases. No
test freezes the system date.
1. **Default** — resolve `{ version: 'v2.2.0-beta' }`; assert breadcrumb "Settings", title
"Settings", subtitle "Workspace information.", one row with the label "Version" and the value
exactly "v2.2.0-beta", `request` called once with `/v1/settings`, and no button, link, switch or
input inside the card.
2. **No prefix** — resolve `{ version: 'dev' }`; assert the value text is exactly "dev".
3. **Navigation** — assert the sidebar and the drawer list Home, Articles, Users, Integration,
Settings in that order with the settings icon on the last; on /settings only "Settings" carries
`aria-current="page"`.
4. **Loading** — unresolved request; at 149 ms assert no skeleton and that "Version" is present; at
150 ms assert a skeleton in place of the value and `aria-busy="true"` on the card; resolve and
assert the value and no `aria-busy`.
5. **Error, Examples-driven** — reject with `ApiError(500)`, then `NetworkError`; assert the alert
text "Couldn't reach RenewCMS. Check your connection and try again.", the "Try again" action, no
close button, no title and no "Version" row, with the header still shown. Click "Try again";
assert Loading and a second `request`; resolve and assert the Default row.
6. **401** — reject with `ApiError(401)`; assert the page shows no alert of its own (the redirect
itself is covered by `useApi`'s existing tests).
7. **Router meta** — assert the `/settings` route has `meta.auth === 'verified'` and
`meta.title === 'Settings'`.
8. **Amended shell specs** — update the existing Vitest for `nuxt_ui_shell_foundation` case 14,
`dashboard_shell_branding`, users_screen and profile_page to five nav items, in the same change.
## Visual (`task visual:check -- settings`, desktop and mobile, light and dark)
Reference: `docs/design/screens/settings.md`; board group "Settings" in `docs/design/source/RenewCMS
Screens Back-office.dc.html`; exact values from the `isSettings` block of
`docs/design/source/AppFrame.dc.html`. Add the mock to `web/visual/states.ts`. The gate is hard:
every capture within 10 %.
- [ ] Default: mock `GET /v1/settings` returning `{ "version": "v2.2.0-beta" }` (the board's
sample). Layout as the frame draws it: the header is a 20/28 semibold title with the muted
subtitle 2 px below; the card is the header's next sibling, 20 px below; the card is
`--ui-bg` with a 1 px `--ui-border` and no drawn radius; the row is a flex row with
`justify-content: space-between`, `align-items: center` and a 16 px gap, the label at the
left and the mono value at the right; the whole page is at most 720 px wide.
- [ ] Not drawn, no visual state: Loading and Error. Do not add them to `web/visual/states.ts`;
Vitest cases 4 and 5 cover them.
- [ ] Not covered by screenshots: keyboard order (Tab reaches the "Settings" nav item; on Error,
Tab reaches "Try again", and Enter and Space activate it); focus after a navigation; the
skeleton pulse under reduced motion.
## Manual verification
- With a build made through `task build` or `task release` (`-ldflags -X main.version=...`),
open /settings and confirm the value equals the injected version. A build without the flag must
show `dev`.
- Confirm against a running `task dev` API that an unverified account is sent to /register/pending
and a logged-out browser to /login?redirect=/settings&reason=expired.
- Confirm the embedded SPA (built without `-tags nofrontend`) serves /settings on a hard refresh,
since Vitest never exercises the embedded frontend.
+8 -3
View File
@@ -37,9 +37,12 @@ Feature: Uploading an image to an article
back to a generic 500
And PostImage reads the uploaded file from the multipart form field
"file"
And on success PostImage answers 201 with a JSON body {"location": ...}
holding the created image's public path, e.g.
"/static/uploadedImages/<stored-filename>"
And on success PostImage answers 201 with a JSON body
{"id": ..., "location": ...} holding the created image's numeric id
and public path, e.g. "/static/uploadedImages/<stored-filename>"
And this slice (features/remove_article_image.feature) adds the "id"
field to that body; the id lets a client later address the image
through DELETE /v1/article/{id}/image/{imageId}
Scenario: Uploading an allowed image type to an existing article succeeds
Given a valid jwt cookie for a user with id 1
@@ -51,6 +54,8 @@ Feature: Uploading an image to an article
Then the response status is 201
And the response body is JSON with a "location" field whose value is
"/static/uploadedImages/before.png"
And the response body's "id" field equals the new image's id in the
image repository
And the image repository contains a new image whose Path is
"/static/uploadedImages/before.png"
And the article repository's article with id 1 has that new image's id
+242
View File
@@ -0,0 +1,242 @@
Feature: A verified user can set an optional display name that replaces their username for display only
As one of several admins with equal access to a RenewCMS workspace
I want to give my account an optional display name, up to 60 characters, and have the API
return it wherever my own account is returned
So that people are named by a human name instead of a username, while logging in still uses
the username and no secret field ever reaches a response
Background:
Given internal/domain/user gains the field DisplayName, json "display_name", with no gorm tag,
and the sentinel user.ErrInvalidDisplayName
And user.Repository gains UpdateDisplayName(userId uint32, displayName string) (User, error),
returning user.ErrUserNotFound when the user does not exist
And the persistence model stores the display name in a column whose default is the empty
string, so rows created before this slice still load with DisplayName ""
And a new use case, UpdateUserProfile, exposes UpdateDisplayName(userId uint32, displayName
string) (user.User, error) and depends only on user.Repository
And UpdateUserProfile trims the value with strings.TrimSpace, then counts what remains with
utf8.RuneCountInString (runes, not bytes), returns user.ErrInvalidDisplayName without calling
the repository when the count is above 60, and otherwise hands the trimmed value to
UpdateDisplayName; an empty or whitespace-only value therefore stores "" and clears the name
And api/pkg/apperr defines DisplayNameErrorMessage as "Display name must be 60 characters or
fewer."
And PATCH /v1/user/me is served by a new handler in api/handlers/user/, mounted by a new
/v1/user router in api/router.go inside a group carrying jwtauth.Verifier,
jwtauth.Authenticator, middleware.RequireCurrentToken and middleware.RequireVerifiedUser, in
that order, so an unauthenticated caller is refused with 401, a stale token with 401
apperr.UnauthorizedErrorMessage, and an unverified caller with 403
apperr.VerificationRequiredErrorMessage before the handler runs
And the request body is JSON {"display_name": <string>}; the request struct field is a
*string tagged validate:"required" and is checked with validator.Validate.Struct; a body that
is not valid JSON, a display_name that is not a string, or a missing or null display_name
answers 400
And the handler maps user.ErrInvalidDisplayName to 400 with body
apperr.DisplayNameErrorMessage, user.ErrUserNotFound to 401 apperr.UnauthorizedErrorMessage,
and any other error to 500 "Internal server error", all as plain text from http.Error
And the public user struct and its converter move out of api/handlers/auth into a shared
package under api/pkg, imported by both the auth and user handlers, so neither handler
imports the other
And on success the response is 200 and the body is the updated user in that public shape:
exactly id, username, email, is_verified, created_at, updated_at and display_name
And GET /v1/auth/me and POST /v1/auth/verify use that same public shape, so display_name is
present in both, as "" when unset
And password, password_reset_code, verification_code, verification_expiration,
password_reset_expiration and token_version never appear in any response
(features/user_response_field_hygiene.feature)
And POST /v1/auth/login still authenticates with the username only; display_name is neither
accepted nor matched there
And changing the display name does not change token_version, so existing sessions stay valid
Scenario: A verified user sets a display name
Given a user repository containing user id 7, username "marta", email "marta@renew.example",
is_verified true, DisplayName "", TokenVersion 0
And a valid jwt cookie for user id 7 encoding token_version 0
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": "Marta Alves"}
Then the response status is 200
And the response body is a JSON object with exactly the keys id, username, email, is_verified,
created_at, updated_at and display_name
And the response body's id is 7, username "marta", display_name "Marta Alves"
And the user repository now holds DisplayName "Marta Alves" for user id 7
And the user repository still holds username "marta"
Scenario Outline: The value is trimmed before it is stored and returned
Given a user repository containing user id 7, username "marta", is_verified true, DisplayName ""
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": <sent>}
Then the response status is 200
And the response body's display_name is <returned>
And the user repository holds DisplayName <returned> for user id 7
Examples:
| sent | returned |
| " Marta Alves " | "Marta Alves" |
| "\tMarta Alves\n" | "Marta Alves" |
| "Marta Alves" | "Marta Alves" |
Scenario Outline: An empty or whitespace-only value clears the display name
Given a user repository containing user id 7, username "marta", is_verified true, DisplayName
"Marta Alves"
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": <sent>}
Then the response status is 200
And the response body's display_name is ""
And the response body's username is "marta"
And the user repository holds DisplayName "" for user id 7
Examples:
| sent |
| "" |
| " " |
| "\t \n" |
Scenario Outline: The limit is 60 Unicode characters, counted as runes
Given a user repository containing user id 7, username "marta", is_verified true, DisplayName ""
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and a display_name of <count> repetitions
of <unit>
Then the response status is <status>
And <effect>
Examples:
| count | unit | status | effect |
| 60 | "a" | 200 | the repository holds that 60-character value |
| 61 | "a" | 400 | the body is apperr.DisplayNameErrorMessage and DisplayName is still "" |
| 60 | "😀" | 200 | the repository holds that 60-rune value (240 bytes) |
| 61 | "😀" | 400 | the body is apperr.DisplayNameErrorMessage and DisplayName is still "" |
| 60 | "é" | 200 | the repository holds that 60-rune value (120 bytes) |
Scenario: The limit applies after trimming, not before
Given a user repository containing user id 7, username "marta", is_verified true, DisplayName ""
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and a display_name made of 5 spaces,
60 "a" characters and 5 spaces (70 characters in total)
Then the response status is 200
And the response body's display_name is the 60 "a" characters
Scenario: Control characters inside the name are kept
Given a user repository containing user id 7, username "marta", is_verified true, DisplayName ""
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": "Ma\nrta"}
Then the response status is 200
And the response body's display_name is "Ma\nrta"
Scenario: A rejected value leaves the existing display name untouched
Given a user repository containing user id 7, username "marta", is_verified true, DisplayName
"Marta Alves"
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and a display_name of 61 "a" characters
Then the response status is 400
And the repository's UpdateDisplayName is never called
And the user repository still holds DisplayName "Marta Alves" for user id 7
Scenario Outline: A malformed body is refused with 400
Given a user repository containing user id 7, username "marta", is_verified true, DisplayName
"Marta Alves"
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and <body>
Then the response status is 400
And the repository's UpdateDisplayName is never called
And the user repository still holds DisplayName "Marta Alves" for user id 7
Examples:
| body |
| the raw text not json |
| {} |
| {"display_name": null} |
| {"display_name": 42} |
| {"displayName": "Marta"} |
Scenario: The password, token version and login username are unaffected by a display name
Given a user repository containing user id 7, username "marta", is_verified true, a stored
password hash, DisplayName "", TokenVersion 0
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": "Marta Alves"}
Then the response status is 200
And the stored password hash for user id 7 is unchanged
And the stored TokenVersion for user id 7 is unchanged
And the same jwt cookie still gets 200 from GET /v1/auth/me
Scenario: GET /v1/auth/me returns the display name once set
Given a user repository containing user id 7, username "marta", is_verified true, DisplayName
"Marta Alves"
And a valid jwt cookie for user id 7
When the client sends GET /v1/auth/me with that cookie
Then the response status is 200
And the response body has display_name "Marta Alves" and username "marta"
Scenario: GET /v1/auth/me returns an empty display_name, not a missing key, when none is set
Given a user repository containing user id 8, username "bob", is_verified false, DisplayName ""
And a valid jwt cookie for user id 8
When the client sends GET /v1/auth/me with that cookie
Then the response status is 200
And the response body is a JSON object with exactly the keys id, username, email, is_verified,
created_at, updated_at and display_name
And the response body's display_name is ""
Scenario: Logging in still uses the username only
Given a user repository containing verified user "marta" with a known password and DisplayName
"Ines Duarte"
When the client sends POST /v1/auth/login with username "Ines Duarte" and the correct password
Then the response status is 403
And the response body is apperr.LogsErrorMessage
When the client sends POST /v1/auth/login with username "marta" and the correct password
Then the response status is 200
Scenario: An unverified user is refused
Given a user repository containing user id 8, username "bob", is_verified false, DisplayName ""
And a valid jwt cookie for user id 8
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": "Bob"}
Then the response status is 403
And the response body is the apperr.VerificationRequiredErrorMessage text
And the user repository still holds DisplayName "" for user id 8
Scenario: No jwt cookie is refused
Given a user repository containing user id 7, username "marta", is_verified true
When the client sends PATCH /v1/user/me with no jwt cookie and body {"display_name": "Marta"}
Then the response status is 401
And the repository's UpdateDisplayName is never called
Scenario: A stale jwt is refused
Given a user repository containing user id 7, username "marta", is_verified true, TokenVersion 1
And a jwt cookie for user id 7 encoding token_version 0
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": "Marta"}
Then the response status is 401
And the response body is the apperr.UnauthorizedErrorMessage text
And the repository's UpdateDisplayName is never called
Scenario: A jwt minted for a since-deleted account is refused
Given a user repository containing no user with id 999
And a valid jwt cookie for user id 999
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": "Marta"}
Then the response status is 401
And the response body is the apperr.UnauthorizedErrorMessage text
Scenario: A repository failure while saving answers 500
Given a user repository containing user id 7, username "marta", is_verified true
And the user repository fails on its next call to UpdateDisplayName
And a valid jwt cookie for user id 7
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": "Marta"}
Then the response status is 500
And the response body is the text "Internal server error"
Scenario: The user is deleted between authentication and the save
Given a user repository whose UpdateDisplayName returns user.ErrUserNotFound for user id 7
And a valid jwt cookie for user id 7 that passes the middleware
When the client sends PATCH /v1/user/me with that cookie and body {"display_name": "Marta"}
Then the response status is 401
And the response body is the apperr.UnauthorizedErrorMessage text
Scenario Outline: The use case enforces the same rule without HTTP
Given a fake user repository containing user id 7 with DisplayName "Old"
When UpdateUserProfile.UpdateDisplayName is called for user id 7 with <input>
Then the result is <outcome>
Examples:
| input | outcome |
| " Marta " | the user with DisplayName "Marta" |
| "" | the user with DisplayName "" |
| " " | the user with DisplayName "" |
| 60 "😀" runes | the user with those 60 runes |
| 61 "😀" runes | user.ErrInvalidDisplayName (errors.Is), repository not called |
| "Marta" for unknown user id 99 | user.ErrUserNotFound (errors.Is) |
+127
View File
@@ -0,0 +1,127 @@
# QA procedure: user_display_name
Package: `test` (black-box), extending `test/user_test.go` (`mockUserRepo`, `stubHasher`) and
following the router wiring pattern in `test/get_current_user_http_test.go`. No live server, no real
SQLite file, no real SMTP. Files: `test/user_display_name_test.go` (use case and HTTP).
## Test infrastructure additions needed first
1. Add `UpdateDisplayName(userId uint32, displayName string) (user.User, error)` to `mockUserRepo`:
call `m.fail.trigger("UpdateDisplayName")` first, return `user.ErrUserNotFound` when the id is
absent, otherwise store `DisplayName` on the map entry and return it. Add fields
`updateDisplayNameCalls int` and `lastUpdateDisplayName string`.
2. Use `failNext("UpdateDisplayName")` for the 500 case. For the "deleted between auth and save"
case, add `failNextWith("UpdateDisplayName", user.ErrUserNotFound)` (as planned in
`features/article_title_rules.qa.md` step 1), or seed the user, then delete it from the fake after
the middleware step via a hook.
3. Any other type implementing `user.Repository` in `test/` must gain the method so the package
compiles.
## Setup shared by every HTTP case
4. Call `validator.InitValidator()`.
5. `getUser := useCases.NewGetUserUseCase(userRepo)`, `update :=
useCases.NewUpdateUserProfileUseCase(userRepo)`, `userHandler := user.NewHandler(update)` (import
`RenewCMS/api/handlers/user` under an alias that does not collide with the domain `user`
package), `meHandler := auth.NewMeHandler(getUser)`.
6. Fresh `chi.NewRouter()` mirroring `api/router.go`, with `token := jwtauth.New("HS256",
[]byte("test-secret"), nil)`:
```go
r.Route("/v1/user", func(r chi.Router) {
r.Use(jwtauth.Verifier(token))
r.Use(jwtauth.Authenticator(token))
r.Use(middleware.RequireCurrentToken(getUser))
r.Use(middleware.RequireVerifiedUser(getUser))
r.Patch("/me", userHandler.UpdateMe)
})
r.Route("/v1/auth", func(r chi.Router) {
r.Use(jwtauth.Verifier(token))
r.Use(jwtauth.Authenticator(token))
r.Use(middleware.RequireCurrentToken(getUser))
r.Get("/me", meHandler.Me)
})
```
Add the public `/v1/auth/login` route (real `auth.NewLoginHandler` over the fakes, as in the
existing login tests) for the login case. The handler method names above are indicative; use
whatever the handlers expose.
7. Mint cookies with `token.Encode(map[string]any{"user_id": uint32(id), "token_version":
uint32(v)})` set as the `jwt` cookie.
8. Decode success bodies into `map[string]json.RawMessage` (not `user.User`) so key sets can be
asserted. Error bodies are plain text from `http.Error` and carry a trailing `"\n"`.
## Use-case checks (fake repo, no HTTP)
9. `useCases.NewUpdateUserProfileUseCase(repo)` with user id 7 seeded, `DisplayName: "Old"`:
- `" Marta "` -> `DisplayName "Marta"` returned and stored.
- `""` and `" "` -> `DisplayName ""` stored (cleared).
- `strings.Repeat("😀", 60)` -> success. `strings.Repeat("😀", 61)` -> `errors.Is(err,
user.ErrInvalidDisplayName)`, `updateDisplayNameCalls == 0`, stored value still `"Old"`.
- Unknown id 99 -> `errors.Is(err, user.ErrUserNotFound)`.
- Repository failure via `failNext("UpdateDisplayName")` -> the error is returned unchanged.
## HTTP checks
10. Seed user 7 (`marta`, `marta@renew.example`, `IsVerified: true`, `DisplayName: ""`,
`TokenVersion: 0`) with a non-empty `Password` hash. `PATCH /v1/user/me`
`{"display_name":"Marta Alves"}` -> `200`. Body keys are exactly `{id, username, email,
is_verified, created_at, updated_at, display_name}`. `display_name` is `"Marta Alves"`,
`username` is `"marta"`. The repo holds `"Marta Alves"`. The stored `Password` and
`TokenVersion` are unchanged. The same cookie then gets `200` from `GET /v1/auth/me`.
11. Trim table: `" Marta Alves "` and `"\tMarta Alves\n"` -> `"Marta Alves"`; `"Marta Alves"`
keeps its interior spaces.
12. Clear table (seed `DisplayName: "Marta Alves"`): `""`, `" "`, `"\t \n"` -> `200`, response and
repo `display_name ""`, `username` still `"marta"`.
13. Length table (seed `""`): 60 x `"a"` -> `200`; 61 x `"a"` -> `400` with body
`apperr.DisplayNameErrorMessage + "\n"`; 60 x `"😀"` -> `200`; 61 x `"😀"` -> `400`; 60 x `"é"`
-> `200`. Assert `updateDisplayNameCalls == 0` on every `400` and that the stored value is
unchanged.
14. Trim-before-count: `strings.Repeat(" ", 5) + strings.Repeat("a", 60) + strings.Repeat(" ", 5)`
-> `200`, returned value is the 60 `"a"`.
15. Control characters: `{"display_name":"Ma\nrta"}` -> `200`, returned and stored value is
`"Ma\nrta"`.
16. Malformed table (seed `DisplayName: "Marta Alves"`): raw text `not json`, `{}`,
`{"display_name":null}`, `{"display_name":42}`, `{"displayName":"Marta"}` -> each `400`,
`updateDisplayNameCalls == 0`, stored value unchanged. Do not assert an exact body for these.
17. `GET /v1/auth/me` for user 7 with `DisplayName "Marta Alves"` -> `200`, `display_name` is
`"Marta Alves"`. For user 8 (`IsVerified: false`, `DisplayName ""`) -> key set is exactly the
seven keys and `display_name` is `""`, not absent.
18. Login: seed verified user `marta` with a stub-hashed password and `DisplayName: "Ines Duarte"`.
`POST /v1/auth/login` with username `"Ines Duarte"` -> `403`, body
`apperr.LogsErrorMessage + "\n"`. With username `"marta"` -> `200`. Confirm the login handler's
real status for an unknown username before asserting `403`.
19. Unverified user 8 with matching cookie -> `PATCH` -> `403`, body
`apperr.VerificationRequiredErrorMessage + "\n"`, `updateDisplayNameCalls == 0`.
20. No cookie -> `401` (do not assert the body; produced by `jwtauth.Authenticator`),
`updateDisplayNameCalls == 0`.
21. User 7 with `TokenVersion: 1`, cookie encoding `token_version 0` -> `401`, body
`apperr.UnauthorizedErrorMessage + "\n"`, `updateDisplayNameCalls == 0`.
22. Cookie for user 999 that does not exist -> `401`, same body.
23. `failNext("UpdateDisplayName")` (generic error) with a valid verified user -> `500`, body
`"Internal server error\n"`.
24. Repository returns `user.ErrUserNotFound` from `UpdateDisplayName` only (middleware passes) ->
`401`, body `apperr.UnauthorizedErrorMessage + "\n"`.
25. Sweep for secrets: on every `200` PATCH body and on `GET /v1/auth/me`, reuse
`assertNoForbiddenKeys` from `test/user_response_field_hygiene_test.go`. Add `token_version` to
that helper's forbidden keys if it does not check it yet.
## Edits to existing tests required by the six to seven field change
26. `test/user_response_field_hygiene_test.go` (`expectedKeys` in the verify test, around line 127):
add `"display_name"`. The count check then expects seven. The seeded user 7 has no display
name, so also assert `display_name` decodes to `""`.
27. `test/get_current_user_http_test.go` decodes into the public user struct; update its import to
the shared package. Step 17 is the authoritative shape check for `/me`.
## Manual verification (not exercised by the Go test)
- Start an existing dev SQLite file created before this slice, boot the server so `AutoMigrate`
runs, and confirm `GET /v1/auth/me` for the pre-existing user returns `display_name: ""` and that
login still works. Then `PATCH`, restart, and confirm the value persisted.
- Confirm by inspection that the `internal/domain/user` struct has no `gorm` tag on `DisplayName`,
the GORM tag with the empty-string default sits in `persistence/models`, `persistence/mappers`
maps both directions, and the model list in `api/dependecyInjection.go` needs no new entry (same
model, new column).
- Confirm that the new handler package constructs nothing and only receives `UpdateUserProfile`
via `NewHandler(...)`, that `dependecyInjection.go` wires the use case into the `*UseCases`
container, and that neither handler package imports the other.
- No SMTP or real embedded frontend is involved. The SPA is out of scope.
+8 -7
View File
@@ -7,11 +7,11 @@ Feature: API responses never expose a user's secret fields
credential or a still-valid reset/verification secret
Background:
Given the public shape of a user in any API response is exactly six fields: id, username,
email, is_verified, created_at and updated_at
And password, password_reset_code, verification_code, verification_expiration and
password_reset_expiration never appear in any response body, under any key name, regardless
of their value or whether they are set
Given the public shape of a user in any API response is exactly eight fields: id, username,
email, is_verified, created_at, updated_at, display_name and role
And password, password_reset_code, verification_code, verification_expiration,
password_reset_expiration and token_version never appear in any response body, under any key
name, regardless of their value or whether they are set
Scenario: A successful verification response carries only public fields
Given a user repository containing user id 7, username "alice", email "alice@example.com",
@@ -21,10 +21,11 @@ Feature: API responses never expose a user's secret fields
When the client sends POST /v1/auth/verify with body {"code": "abc123"}
Then the response status is 200
And the response body is a JSON object with exactly the keys id, username, email,
is_verified, created_at and updated_at
is_verified, created_at, updated_at, display_name and role
And the response body does not contain the keys password, password_reset_code,
verification_code, verification_expiration or password_reset_expiration
verification_code, verification_expiration, password_reset_expiration or token_version
And the response body's is_verified is true
And the response body's display_name is ""
Scenario: A rejected verification attempt never echoes any user field
Given a user repository containing user id 7, username "alice", is_verified false, whose
+6 -4
View File
@@ -21,10 +21,12 @@ Package: `test` (black-box), extending `test/account_verification_http_test.go`'
user id 7. Decode the response body into `map[string]json.RawMessage` (not into `user.User`)
and assert:
- the key set is exactly `{"id", "username", "email", "is_verified", "created_at",
"updated_at"}`;
"updated_at", "display_name", "role"}`;
- none of `password`, `password_reset_code`, `verification_code`,
`verification_expiration`, `password_reset_expiration` is present;
- `is_verified` unmarshals to `true`.
`verification_expiration`, `password_reset_expiration`, `token_version` is present;
- `is_verified` unmarshals to `true`;
- `display_name` unmarshals to `""`;
- `role` unmarshals to `"owner"` (seeded user 7 has `Role: owner`).
5. Rejected verify: same seed, `{"code":"wrong-code"}` → assert status `403` and that the raw
response body bytes, treated as a string, contain none of the substrings `password`,
`verification_code`, `password_reset_code`, `verification_expiration`,
@@ -55,6 +57,6 @@ Package: `test` (black-box), extending `test/account_verification_http_test.go`'
render; confirm by hand that no SPA code reads `password`, `verification_code` or
`password_reset_code` off the verify response, since removing them from the wire format could
otherwise silently break a screen that isn't covered by this Go test suite.
- Confirm the new response type lives in `api/handlers/auth` (not a change to
- Confirm the public response type lives in the shared package under `api/pkg` (not a change to
`internal/domain/user/userDomain.go`'s json tags), per the project's stated preference to keep
the domain struct's tags intact and shape the public response in the handler layer instead.
+114
View File
@@ -0,0 +1,114 @@
Feature: Users have a role, owner or admin, and only the owner can invite
As the person who registered the workspace
I want my account to be the owner and everyone I invite to be an admin
So that only I can invite people, while every admin keeps the same access to articles,
the users list, their own profile and Settings
Background:
Given a user has a role that is exactly "owner" or "admin", stored on the user record and read
from the user repository on every request, never from the jwt claims
And the first registered user is the owner: CreateUser creates the user with role "owner",
and registration is only possible while no verified user exists
And every user created by accepting an invite is an admin: AcceptInvite creates the user with
role "admin", whatever the inviter's role
And there is exactly one owner and no endpoint changes, transfers or removes a role
And AutoMigrate adds the role column to existing databases and backfills it: the user with the
lowest id becomes "owner" and every other user "admin"; a database that already has roles
is left unchanged by a later start
And the public user shape (api/pkg/publicuser) is id, username, email, is_verified, created_at,
updated_at, display_name and role
And the users list user items are id, kind, username, display_name, email, role, status,
created_at; invite items are unchanged: id, kind, email, status, created_at
And POST /v1/user/invite is owner-only: after the jwt, current-token and verified checks, a
RequireOwner check loads the user with GetUserUseCase and refuses any role other than
"owner" with 403 and the plain-text body apperr.OwnerRequiredErrorMessage
"Only the owner can do this.", before the rate limiter, the body decoding and the validation
And GET /v1/user/ stays open to every verified user, owner and admin alike
And error responses are plain text from http.Error, success responses are JSON
Scenario: The first registered user is the owner
Given the user repository is empty
When the client sends POST /v1/auth/register with username "marta", password "hunter2example12",
email "marta@renew.example"
Then the response status is 200
And the user repository holds one user with username "marta" and role "owner"
Scenario: A user created by accepting an invite is an admin
Given a verified owner "marta" and a pending invite for "lea.martin@renew.example" with a known raw code
When the client sends POST /v1/auth/invite/accept with that code, username "lea" and password "limewash2026"
Then the response status is 200
And the user repository holds user "lea" with role "admin"
And user "marta" still has role "owner"
Scenario Outline: GET /v1/auth/me returns the role of the session user
Given a verified user "<username>" with role "<role>" and a valid jwt cookie for that user
When the client sends GET /v1/auth/me
Then the response status is 200
And the response body has the key role with value "<role>"
Examples:
| username | role |
| marta | owner |
| lea | admin |
Scenario: An unverified owner sees their role on /auth/me
Given an unverified user "bob" with role "owner" and a valid jwt cookie
When the client sends GET /v1/auth/me
Then the response status is 200
And the response body's role is "owner" and is_verified is false
Scenario: The users list carries email and role on accepted users
Given verified owner id 1 "marta" with email "marta@renew.example"
And admin id 2 "jonas" with email "jonas@renew.example"
And admin id 3 "ines" with display_name "Inès Duarte" and email "ines.duarte@renew.example"
And a pending invite for "sam.oliveira@renew.example"
When the client sends GET /v1/user/ with a valid jwt cookie for user id 2
Then the response status is 200
And the user items have exactly the keys id, kind, username, display_name, email, role, status, created_at
And user 1 has email "marta@renew.example" and role "owner"; users 2 and 3 have role "admin" and their own email
And the invite item has exactly the keys id, kind, email, status, created_at
And no item has a key named password, password_reset_code, verification_code,
verification_expiration, password_reset_expiration, token_version, code, hashed_code,
invited_by or accepted_at
Scenario: The owner can invite
Given a verified owner id 1 "marta" and a valid jwt cookie for user id 1
When the client sends POST /v1/user/invite with body {"email": "sam.oliveira@renew.example"}
Then the response status is 201
And one invite exists and one "invitation" email was sent
Scenario: An admin cannot invite
Given a verified admin id 2 "jonas" and a valid jwt cookie for user id 2
When the client sends POST /v1/user/invite with body {"email": "sam.oliveira@renew.example"}
Then the response status is 403
And the response body is exactly apperr.OwnerRequiredErrorMessage, as plain text
And the invite repository is still empty
And no email was sent
Scenario Outline: The owner check comes before validation and the rate limiter
Given a verified admin id 2 and a valid jwt cookie for user id 2
When the client sends POST /v1/user/invite with body <body>
Then the response status is 403
And no invite was created and no email was sent
Examples:
| body |
| {"email": "not-an-email"} |
| not json |
Scenario: An admin's refused invites do not use up the rate limit
Given AUTH_RATE_LIMIT_MAX_ATTEMPTS is 2 for a window covering the whole test
When an admin at IP "203.0.113.20" sends 3 POST /v1/user/invite requests
Then all 3 responses are 403 and none is 429
Scenario: The role is read on every request, not from the token
Given a verified user id 2 whose stored role is "owner", with a valid jwt cookie
And the stored role changes to "admin" without the token changing
When the client sends POST /v1/user/invite with a valid body
Then the response status is 403
Scenario: An admin can still list users
Given a verified admin id 2 and a valid jwt cookie for user id 2
When the client sends GET /v1/user/
Then the response status is 200
+55
View File
@@ -0,0 +1,55 @@
# QA procedure: user_roles
Package: `test` (black-box). Reuse `mockUserRepo`, `stubHasher`, `mockMailRepo`, `mockInviteRepo`.
No live server, no real SQLite file, no real SMTP.
## Setup shared by every case
1. Call `validator.InitValidator()` once.
2. Use cases: `NewGetUserUseCase`, `NewCreateInviteUseCase`, `NewListUsersAndInvitesUseCase`,
`NewCreateUserUseCase`, `NewAcceptInviteUseCase` over the fakes.
3. Router mirrors `NewUserRouter`: `jwtauth.Verifier` + `Authenticator` with
`jwtauth.New("HS256", []byte("test-secret"), nil)`, `RequireCurrentToken`, `RequireVerifiedUser`,
`GET /`, and a group with `RequireOwner(getUser)`, `TrustedProxyRealIP(nil)`,
`NewRateLimiter(2, time.Minute)`, `POST /invite`. A second router mirrors `NewAuthRouter` for
`/register`, `/invite/accept` and `/me`.
4. Seed: owner id 1 "marta" (role owner), admin id 2 "jonas" (role admin), both verified.
Cookies carry `user_id` and `token_version`, and never a role.
## Roles at creation
5. Empty repo, `POST /v1/auth/register` -> 200, the stored user has `Role == user.RoleOwner`.
6. Pending invite with a known code (stubHasher), `POST /v1/auth/invite/accept` -> 200, the stored
user has `Role == user.RoleAdmin`, and user 1 is still owner.
7. Use-case level: `CreateUser` returns a user with `RoleOwner`; `AcceptInvite` returns `RoleAdmin`.
## GET /v1/auth/me
8. Table over owner and admin: 200, decode into `map[string]json.RawMessage`, key `role` equals the stored role.
9. Unverified owner -> 200, `role` "owner", `is_verified` false.
10. The key set of the public user is exactly the eight fields, and `POST /v1/auth/verify` returns the same eight.
## GET /v1/user/
11. Seed three users plus a pending invite. 200; user items have exactly the keys id, kind, username,
display_name, email, role, status, created_at; email and role match the seed. The invite item has
exactly id, kind, email, status, created_at. No forbidden key appears anywhere.
12. Cookie of admin 2 -> 200.
## POST /v1/user/invite
13. Owner cookie, valid body -> 201, one invite, one "invitation" mail.
14. Admin cookie, valid body -> 403, body exactly `apperr.OwnerRequiredErrorMessage`, `Content-Type`
is not JSON-decoded (plain text), no invite, no mail.
15. Admin cookie with `{"email":"not-an-email"}` and with `not json` -> 403 both.
16. Rate limit 2: admin sends 3 requests -> 403, 403, 403.
17. Flip user 2's stored role from owner to admin between two requests with the same cookie ->
second request 403.
18. Existing auth table from invitations.qa.md (no cookie 401, unverified 403, stale token 401) is
unchanged; the unverified 403 body remains `apperr.VerificationRequiredErrorMessage`.
## Use case level
19. `RequireOwner` with a user id that no longer exists -> 401 `apperr.UnauthorizedErrorMessage`;
with an unexpected repository error -> 500.
## Manual verification (not exercised by the Go tests)
- Persistence backfill: copy a SQLite file from before this change with 3 users and no role column.
Start the app: the column exists, the lowest id is `owner`, the others `admin`. Restart: nothing
changes. Start against a fresh file: registering creates an owner.
- Layering check by review: `Role` and the sentinel/constants live in `internal/domain/user`; GORM
tags only in `persistence/models`, converted by the mapper.
+174
View File
@@ -0,0 +1,174 @@
Feature: Users row actions: Cancel invite and Renew invite
As the owner of a RenewCMS workspace
I want to cancel a pending invite and renew an expired one from the Users list
So that I can correct a wrong address or resend a lapsed link without leaving the page
Background:
Given /users is the verified route of features/users_screen.feature, rendered as UsersPage with
UsersTable (md and up) or UserCardList (below md), per docs/design/screens/users.md
And the backend already exists (features/invite_management.feature) and this slice changes no Go:
DELETE /v1/user/invite/{id} answers 204 with an empty body, and POST /v1/user/invite/{id}/renew
answers 200 with {id, kind "invite", email, status "pending", created_at, expires_at}
And useUsers gains cancelInvite(id), which sends DELETE /v1/user/invite/{id} with no body, and
renewInvite(id), which sends POST /v1/user/invite/{id}/renew with no body
And the actions are shown only when the session user's role from GET /v1/auth/me is "owner";
for "admin", or any other or absent value, no action button is rendered and the sixth column
stays empty; this is not drawn in docs/design, so it has no visual state and is covered
by Vitest only
And the sixth column (desktop) or the last line of the card (below md) holds at most one
action: "Cancel invite" on a Pending row, "Renew invite" on an Expired row, nothing on an
Accepted row
And each action is an outline button: 28 px high on desktop (12 px medium text, 13 px icon,
9 px side padding, --ui-border-accented border, --ui-bg fill, no wrapping) and 44 px high
below md (14 px side padding, 14 px icon); UButton variant "outline" size "xs"
And "Cancel invite" has the icon user-x and text in --ui-error; "Renew invite" has the icon
refresh-cw and text --ui-text-highlighted
And below md the action is the last line of the card, under the badges line
And "Cancel invite" opens ConfirmDialog (tone "danger") through useOverlay: title "Cancel this
invite?", description "The link sent to {email} will stop working. You can invite the address
again later.", cancel button "Keep invite", confirm button "Cancel invite", pending label
"Cancelling…"; the action runs inside the dialog, so the failure notice shows in the dialog
And "Renew invite" asks nothing and sends the request at once
And a request failure is any 500, any network failure that never reaches the server, and any
other status except 401 and 403; 401 and 403 are handled entirely by useApi's global handling
(features/api_client_global_error_handling.feature); the response body text is never shown
verbatim
And the fixture is the Default fixture of features/users_screen.feature: invite id 2
"sam.oliveira@renew.example" pending 27 Sep 2026; invite id 1 "p.huber@gmail.com" with
display_name "Paul Huber" expired 3 Aug 2026; users 3, 2, 1; the session user is "marta",
role "owner"; rows are keyed by kind and id
Scenario: Default: actions sit on the right of the Pending and Expired rows only
Given GET /v1/user/ resolves 200 with the Default fixture
When the owner navigates to /users at desktop
Then the first row "sam.oliveira@renew.example" ends with "Cancel invite" (icon user-x, text --ui-error)
And the second row "p.huber@gmail.com" ends with "Renew invite" (icon refresh-cw)
And the three Accepted rows have an empty sixth cell
And below md the same two cards end with the same buttons as 44 px buttons
Scenario Outline: Non-owners see no row actions
Given the session user has role "<role>" and GET /v1/user/ resolves 200 with the Default fixture
When the user navigates to /users at desktop and at a below-md width
Then <result>
Examples:
| role | result |
| admin | no "Cancel invite" and no "Renew invite" button exists |
| (none) | no "Cancel invite" and no "Renew invite" button exists |
| owner | "Cancel invite" and "Renew invite" are present once each |
Scenario: Cancel invite: confirm
Given the Default state has loaded
When the owner activates "Cancel invite" on the "sam.oliveira@renew.example" row
Then a danger modal opens titled "Cancel this invite?"
And its text reads "The link sent to sam.oliveira@renew.example will stop working. You can invite
the address again later."
And its buttons are "Keep invite" and "Cancel invite" (danger), and no request has been sent
Scenario: Cancel invite: "Keep invite" closes the dialog and changes nothing
Given the "Cancel this invite?" dialog is open for "sam.oliveira@renew.example"
When the owner activates "Keep invite"
Then the dialog closes, DELETE /v1/user/invite/2 is never sent and all 5 rows remain
Scenario: Cancel invite: sending
Given the "Cancel this invite?" dialog is open for "sam.oliveira@renew.example"
When the owner activates "Cancel invite" and DELETE /v1/user/invite/2 has not resolved
Then DELETE /v1/user/invite/2 was sent once
And the confirm button reads "Cancelling…" with a loading indicator
And "Keep invite" is disabled
And Esc and a backdrop click do not close the dialog
Scenario Outline: Cancel invite: failed
Given the "Cancel this invite?" dialog is open for "sam.oliveira@renew.example"
When the owner activates "Cancel invite" and DELETE /v1/user/invite/2 <failure>
Then the dialog stays open, with an error notice inside it reading "Couldn't cancel the invite.
Try again in a moment."
And "Keep invite" and "Cancel invite" are enabled again
And all 5 rows remain and no toast is raised
Examples:
| failure |
| resolves with a 500 response |
| resolves with a 500 response whose body is some other text |
| never reaches the server |
| resolves with a 404 response |
Scenario: Cancel invite: retrying after a failure
Given the dialog shows the failure notice
When the owner activates "Cancel invite" again and DELETE /v1/user/invite/2 resolves 204
Then DELETE /v1/user/invite/2 was sent a second time
And the dialog closes and the row is removed
Scenario: Cancel invite: done
Given the "Cancel this invite?" dialog is open for "sam.oliveira@renew.example"
When the owner activates "Cancel invite" and DELETE /v1/user/invite/2 resolves 204
Then the dialog closes
And the row "sam.oliveira@renew.example" is gone and the other 4 rows remain in their order
And GET /v1/user/ is not called again
And a toast appears: color success, icon i-lucide-circle-check, id "invite-cancelled-2", title
"Invite cancelled", description "sam.oliveira@renew.example can no longer use the link."
Scenario: Cancel invite: an Expired row can't be cancelled from the list
Given the Default state has loaded
Then the "p.huber@gmail.com" row offers "Renew invite" and no "Cancel invite"
Scenario: Renew invite: sending
Given the Default state has loaded
When the owner activates "Renew invite" on the "p.huber@gmail.com" row and
POST /v1/user/invite/1/renew has not resolved
Then POST /v1/user/invite/1/renew was sent once with no body and no confirmation was shown
And on that row the button reads "Renewing…" with the icon loader-circle at 50 % opacity, disabled
And no other row's button changes and the "Cancel invite" button of "sam.oliveira@renew.example" stays enabled
And a second activation of the busy button sends nothing
Scenario: Renew invite: done
Given POST /v1/user/invite/1/renew was sent from the "p.huber@gmail.com" row
When it resolves 200 with id 1, kind "invite", email "p.huber@gmail.com", status "pending",
created_at now and expires_at 3 days later
Then the row moves to the top of the list as Pending, created "Today", drawn with the
--ui-bg-elevated background, keeping its display name "Paul Huber" and role "admin", and now
ends with "Cancel invite"
And "sam.oliveira@renew.example" is now the second row and the other rows are unchanged
And exactly one row exists for "p.huber@gmail.com" and GET /v1/user/ is not called again
And a toast appears: color success, icon i-lucide-circle-check, id "invite-renewed-1", title
"Invite renewed", description "p.huber@gmail.com has 3 days to accept the new link."
Scenario: Renew invite: renewing a Pending row is not offered
Given the Default state has loaded
Then the "sam.oliveira@renew.example" row offers "Cancel invite" and no "Renew invite"
Scenario Outline: Renew invite: failed
Given the Default state has loaded
When the owner activates "Renew invite" on the "p.huber@gmail.com" row and
POST /v1/user/invite/1/renew <failure>
Then a toast appears: color error, icon i-lucide-circle-x, id "invite-renew-failed-1", title
"Couldn't renew the invite", description "Try again in a moment."
And the row stays Expired in its place, with "Renew invite" enabled again
And the list is otherwise unchanged
Examples:
| failure |
| resolves with a 500 response |
| resolves with a 500 response whose body is some other text |
| never reaches the server |
| resolves with a 404 response |
Scenario: Renew invite: retrying after a failure
Given the failed toast has appeared for "p.huber@gmail.com"
When the owner activates "Renew invite" again and POST /v1/user/invite/1/renew resolves 200
Then the "Invite renewed" toast is raised and the row is Pending on top
Scenario: Renew invite: only the busy row is busy
Given the fixture also holds Expired invite id 7 "old@renew.example"
When the owner activates "Renew invite" on "p.huber@gmail.com" and it has not resolved
Then "Renew invite" on "old@renew.example" is still enabled and can be activated
Scenario: Actions after a new invite is sent
Given the Default state has loaded and an invite for "lea.martin@renew.example" was sent (201)
Then the new first row ends with "Cancel invite"
Scenario: Cancelling a just-renewed row
Given "p.huber@gmail.com" was renewed and is the first row
When the owner confirms "Cancel invite" for it and DELETE /v1/user/invite/1 resolves 204
Then the row is gone and the toast "Invite cancelled" is raised
+98
View File
@@ -0,0 +1,98 @@
# QA: Users row actions (Cancel invite, Renew invite)
## Implementation note for coder (informational, not a QA assertion)
No Go change. Toasts use useToast().add({ id, color, icon, title, description }):
- cancelled: id "invite-cancelled-{id}", color success, icon i-lucide-circle-check, title "Invite cancelled",
description "{email} can no longer use the link."
- renewed: id "invite-renewed-{id}", color success, icon i-lucide-circle-check, title "Invite renewed",
description "{email} has 3 days to accept the new link."
- renew failed: id "invite-renew-failed-{id}", color error, icon i-lucide-circle-x, title "Couldn't renew the invite",
description "Try again in a moment."
Cancel runs through ConfirmDialog (tone "danger", cancelLabel "Keep invite", confirmLabel "Cancel invite",
pendingLabel "Cancelling…"); its action throws an Error whose message is "Couldn't cancel the invite. Try again in
a moment." for any failure except 401/403 (global handling), so the dialog shows it. Remove the 10.5 % exception
from the "users" > Default state in web/visual/states.ts.
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock useApi's `request` for GET /v1/user/, DELETE /v1/user/invite/{id} and POST /v1/user/invite/{id}/renew. Mount
UsersPage inside DashboardShell with a verified owner session (id 1, "marta", role "owner") and a test router at
/users. Default fixture as in features/users_screen.qa.md. No test freezes the system date; the renewed row's
"Today" label is not asserted. Run layout cases at desktop and below-md widths (mock matchMedia).
1. Default actions: row 1 has "Cancel invite" (user-x), row 2 "Renew invite" (refresh-cw), Accepted rows have
none; at below-md the same buttons sit last in the cards.
2. Non-owners, Examples-driven: role "admin", role absent, role "owner"; assert presence or absence of both
buttons at both widths.
3. Cancel invite: confirm: click "Cancel invite" on row 1; assert dialog title, text with the address, "Keep
invite", "Cancel invite", and that `request` was not called with DELETE.
4. Keep invite: click it; assert the dialog closed, no DELETE, 5 rows.
5. Cancel invite: sending: unresolved DELETE; assert one call to DELETE /v1/user/invite/2 (no body), "Cancelling…",
"Keep invite" disabled, Escape and backdrop click do not close.
6. Cancel invite: failed, Examples-driven: ApiError(500), ApiError(500) with other text, ApiError(404),
NetworkError; assert the dialog stays open with the notice "Couldn't cancel the invite. Try again in a moment."
once (never the raw body), buttons re-enabled, 5 rows, no toast.
7. Cancel invite: retry: after 6, resolve 204 on the second click; assert two DELETE calls, dialog closed, row gone.
8. Cancel invite: done: resolve 204; assert dialog closed, row 1 gone, 4 rows in order, no second GET, toast
raised with the id, color, icon, title and description above.
9. 401 and 403 on DELETE and on renew: assert the global handling runs and no local notice or toast is added.
10. Renew invite: sending: unresolved POST; assert one call to POST /v1/user/invite/1/renew with no body, no
dialog, the row-2 button reads "Renewing…", is disabled, has the loader-circle icon and 50 % opacity class; row
1's "Cancel invite" is enabled; a second click sends nothing.
11. Only the busy row is busy: two Expired rows; renew one, assert the other button is enabled and usable.
12. Renew invite: done: resolve 200 with the response shape; assert "p.huber@gmail.com" is first, Pending, has the
--ui-bg-elevated class, keeps "Paul Huber", ends with "Cancel invite", "sam.oliveira@renew.example" second, one
row for the address, no second GET, and the toast (id, color, icon, title, description).
13. Renew invite: failed, Examples-driven: ApiError(500), ApiError(500) with other text, ApiError(404),
NetworkError; assert the error toast, the row still Expired in place, the button enabled again with the label
"Renew invite".
14. Renew retry: after 13, resolve 200; assert the success toast and the row on top.
15. Interplay: a row from a fresh invite (201) shows "Cancel invite"; cancelling a just-renewed row removes it and
raises "Invite cancelled".
16. Invite-only rule: assert no "Renew invite" on a Pending row and no "Cancel invite" on an Expired row.
## Visual (task visual:check -- users, desktop and mobile, light and dark)
Reference: docs/design/screens/users.md; board group "Users" in `docs/design/source/RenewCMS Screens
Back-office.dc.html`; exact values in `docs/design/source/AppFrame.dc.html`. Layout (button size, position in the
sixth column and on the card, dialog geometry) is taken from the board frame, not components.md. The gate is hard:
every capture of every non-skipped state must be within 10 %, both viewports, both themes. Use the board's sample
data: the existing `usersFixture` (sam.oliveira@renew.example pending 27 Sep 2026; p.huber@gmail.com "Paul Huber"
expired 3 Aug 2026), session marta/owner. Add these 7 states to `users` in web/visual/states.ts:
- [ ] Cancel invite: confirm: steps click "Cancel invite" on the sam.oliveira row; dialog "Cancel this invite?" with
text naming sam.oliveira@renew.example, "Keep invite", "Cancel invite".
- [ ] Cancel invite: sending: mock `DELETE /v1/user/invite/2` status 204 with `hang: true`; steps open the dialog and
click "Cancel invite"; "Cancelling…" loading, "Keep invite" disabled.
- [ ] Cancel invite: failed: mock `DELETE /v1/user/invite/2` status 500; steps open the dialog and confirm; the
notice "Couldn't cancel the invite. Try again in a moment." inside the dialog, buttons enabled.
- [ ] Cancel invite: done: `{ path: '/users', skip: 'clock-sensitive' }` (per the user's request; the design does
not mark it clock-sensitive). Prints SKIP, never investigated or date-frozen. Vitest case 8 covers it.
- [ ] Renew invite: sending: mock `POST /v1/user/invite/1/renew` status 200 with `hang: true`; steps click "Renew
invite" on the p.huber row; only that button shows "Renewing…", loader-circle, 50 % opacity.
- [ ] Renew invite: done: `{ path: '/users', skip: 'clock-sensitive' }` ("Today"). Vitest case 12 covers it.
- [ ] Renew invite: failed: mock `POST /v1/user/invite/1/renew` status 500; steps click "Renew invite"; the error
toast "Couldn't renew the invite" / "Try again in a moment." is visible and the p.huber row is Expired with
"Renew invite". Keep the toast on screen for the capture; if the runner can't, stop and ask.
- [ ] Default: with the exception removed it passes at 10 % with the drawn buttons; if it fails, stop and ask (no
exception without approval).
- [ ] Not drawn, no visual state: non-owner rendering and the 404 fallback. Vitest only (cases 2, 6, 13).
- [ ] Not covered by screenshots: keyboard order (Tab reaches each row action; in the dialog focus starts on "Keep
invite", is trapped, Esc closes it except while Cancelling…, focus return after the dialog closes); hover and
active on the buttons; motion (modal 240 ms, toast enter and exit), stopped under reduced motion.
## Manual verification
- Real round trips against `task dev`, as owner: cancel a pending invite (row disappears, the old link at
/invite/accept?c=... answers "This invite link doesn't work."), renew an expired one (row moves to top with
"Today", old link dead, new link works), and reload to confirm the order matches the API.
- Real invitation email on renew needs real or sandboxed SMTP (`SMTP_HOST` and related vars): confirm the new mail
arrives with the new link and the old one no longer works.
- Failure paths with the API stopped or SMTP failing: the renew toast and the cancel dialog notice appear, and a
retry succeeds.
- Admin session against `task dev`: no row actions are shown.
- Toast placement and stacking on desktop (bottom right) and above the pinned "Invite user" button on mobile.
- Focus after a successful cancel (the row is gone) lands somewhere sensible.
- "Today" and the elevated row on a live app after Renew, since visual:check skips it.
+319
View File
@@ -0,0 +1,319 @@
Feature: Users screen and InviteUserModal
As a verified RenewCMS user in the shared workspace
I want /users to list everyone who has an account or an open invite, and let me invite someone
by email from a modal without leaving the page
So that a teammate can sign in with their own account, and I can always see who is in the
workspace and whether their invite is still open
Background:
Given /users is a verified route (meta.auth "verified") rendered as UsersPage inside
DashboardShell, per docs/design/routes.md and docs/design/screens/users.md
And UsersPage calls GET /v1/user/ once per navigation, and InviteUserModal sends POST
/v1/user/invite; both endpoints already exist (features/invitations.feature) and this slice
wires the SPA to them unchanged, with no Go change
And the list items keep the API shape: user items are kind "user" (id, username, display_name,
email, role "owner" or "admin", status "accepted", created_at) or kind "invite" (id, email,
status "pending" or "expired", created_at); the list is used in the order the API returns it
(created date, newest first), and rows are keyed by kind and id, because a user and an
invite can share a numeric id
And DashboardShell's navigation gains "Users" (icon users, linking to /users) between
"Articles" and "Integration", in the sidebar and in the mobile drawer, so it lists Home,
Articles, Users, Integration, Settings in that order; "Users" has aria-current="page" on /users; the
"five navigation destinations" scenario of nuxt_ui_shell_foundation.feature and the items of
dashboard_shell_branding.feature are amended accordingly
And the PageHeader shows breadcrumb "Users" (mobile title "Users")
And the page header is the title "Users" with the subtitle "Everyone who can sign in and work
on your articles." and, on desktop (md and up) for the owner, a primary "Invite user" button
(icon user-plus) at the right of the header
And below md, for the owner, "Invite user" is instead a full-width 48 px button (icon
user-plus) pinned 16 px from the left, right and bottom of the screen with the popover
shadow, and it is hidden while InviteUserModal is open
And "Invite user" (desktop header button and the mobile pinned button) is shown only when the
session user's role from GET /v1/auth/me is "owner"; for "admin", or any other or absent
value, neither button is rendered, the pinned button's bottom space is not reserved, and
the "Only you" hint is hidden; this is not drawn in docs/design, so it has no visual state
and is covered by Vitest only
And the list is rendered as UsersTable (desktop, md and up) or UserCardList (below md), both
fed by the same items array; rows are not clickable; row actions are specified in features/users_row_actions.feature
And UsersTable has the columns Email, Display name, Role, Invite status and Created, plus an
unlabeled, empty actions column kept so the grid matches the board: grid
minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px with a 12 px gap, a 36 px header on
--ui-bg-elevated, 48 px rows with a top border, and an arrow-down icon on the Created header
And UserCardList (below md) has a 68 px minimum row height: the email line (with the "you"
tag), the display name below it only when there is one, then the RoleBadge, the
InviteStatusBadge and "Created {date}" on one line
And the username is not shown anywhere in the list
And the Email cell shows the account's or invite's email address, medium weight, highlighted;
the row whose kind is "user" and whose id equals the session user's id (from GET
/v1/auth/me) carries a muted mono "you" tag after it
And the Display name cell shows the item's display_name, highlighted, or a muted dash "—" when
it is empty or absent; an invite item shows the dash unless it carries a display_name; the
current user's row shows their saved name
And RoleBadge is a 20 px badge, IBM Plex Mono 11 px medium, 7 px side padding, no icon, showing
the word: owner (filled --ui-primary, --ui-bg text, --ui-primary border) or admin
(transparent, --ui-text-toned text, --ui-border-accented border); a user row shows its
role, and an invite row shows "admin", the role it will create
And InviteStatusBadge shows icon and word, never color alone: Accepted (circle-check, success
soft), Pending (mail, warning soft), Expired (clock-alert, transparent, muted, with an
accented border)
And the Created column shows the date as "27 Sep 2026", or "Today" when it is the current day;
the fixture below uses absolute dates only
And skeleton rows (5) show only after 150 ms of loading, so a fast response never flashes them,
one bar per column plus a RoleBadge placeholder and an InviteStatusBadge placeholder in the
table (md and up); the below-md card skeleton keeps the board's two-bar shape
And the Default fixture holds 5 items, newest first: invite id 2 "sam.oliveira@renew.example"
pending 27 Sep 2026; invite id 1 "p.huber@gmail.com" with display_name "Paul Huber" expired
3 Aug 2026; user id 3 "ines" email "ines.duarte@renew.example" display_name "Inès Duarte"
role admin accepted 18 Jun 2026; user id 2 "jonas" email "jonas@renew.example" no display
name, role admin, accepted 2 Apr 2026; user id 1 "marta" email "marta@renew.example" no
display name, role owner, accepted 12 Mar 2026; the session user is id 1 "marta", role
"owner"
And InviteUserModal is a UModal opened from either "Invite user" button; every time it opens it
starts in its default state: title "Invite a user", text "We'll email them a link to choose
a username and password. The link expires after 3 days.", an empty, focused Email field
with placeholder "name@example.com", a "Cancel" button and a "Send invite" button
And the Email field validates on blur and again on submit, then on every input once it shows
an error; an empty value or one that is not a full email address shows "Enter a full email
address, like name@example.com." under the field, sends no request, and moves focus to the
field on a failed submit; the rule mirrors the API's email validation
And activating "Send invite" with a valid address sends POST /v1/user/invite with JSON
{"email": "<value as typed>"}; while the request is in flight the field and "Cancel" are
disabled, the confirm button reads "Sending…" with a loading indicator, and the modal cannot
be dismissed by Cancel, Esc or a backdrop click
And a 201 response closes the modal, inserts the response invite (kind "invite", status
"pending") as the first row of the list without a refetch, removes any other invite row for
the same address (the server replaced an expired one), draws the new row with the
--ui-bg-elevated background until the next load or navigation, and raises a toast: color
success, icon i-lucide-circle-check, id "invite-sent-{id}", title "Invite sent", description
"{email} has 3 days to accept."
And a 409 response never shows a request failure alert: it re-enables the form with the
address kept and shows the field error "This address already has an account." when the
response body is that text, or "There's already a pending invite for this address." when the
body is that text; any other 409 body shows "This address already has an account."
And a 400 response that got past this form's own check re-enables the form with the address
kept and shows the alert "Something in the form isn't valid. Check the highlighted fields."
with the field error "Enter a full email address, like name@example.com."
And a 429 response (the auth rate limiter) re-enables the form with the address kept and shows
the alert "Too many invites. Wait a moment, then try again." above the buttons, with no field
error; this state is not drawn in docs/design, so it has no visual state and is covered by
Vitest only
And a 500 response (including the API's "Couldn't send the invite. Try again in a moment.") or
a request that never reaches the server re-enables the form with the address kept and shows
the alert "Couldn't send the invite. Try again in a moment." above the buttons, with no
field error; the body text is never shown verbatim
And "Cancel" closes the modal immediately, discards the field and sends nothing, whenever the
form is not disabled by an in-flight request; focus returns to the button that opened it
And a 401 and a 403 (unverified) on either endpoint are handled entirely by useApi's global
handling (features/api_client_global_error_handling.feature)
And this slice does not build the accept-invite screen (/invite/accept); the "Display names in the Users list" state of the
Profile group is drawn by this same list
Scenario: Default — the list loads newest first with email, display name, role, status and created
Given GET /v1/user/ resolves 200 with the 5-item Default fixture and the session user is
"marta" with role "owner"
When the user navigates to /users
Then the breadcrumb reads "Users" (mobile title "Users")
And the header shows the title "Users", the subtitle and, on desktop, "Invite user"
And the table header reads Email, Display name, Role, Invite status, Created, and an empty
unlabeled sixth cell
And the rows appear in exactly the fixture's order, each 48 px high
And the first row shows "sam.oliveira@renew.example", "—" (muted), "admin", a Pending badge
and "27 Sep 2026"
And the second row shows "p.huber@gmail.com", "Paul Huber", "admin", an Expired badge and
"3 Aug 2026"
And the third row shows "ines.duarte@renew.example", "Inès Duarte", "admin", an Accepted
badge and "18 Jun 2026"
And the fourth row shows "jonas@renew.example", "—", "admin", an Accepted badge and "2 Apr 2026"
And the fifth row shows "marta@renew.example" with the "you" tag, "—", "owner" (filled), an
Accepted badge and "12 Mar 2026"
And the username "ines", "jonas" or "marta" appears in no row
And below md the same rows render as cards: the email line, the display name below it only
for "p.huber@gmail.com" and "ines.duarte@renew.example", then the RoleBadge, the status
badge and "Created {date}" on one line
Scenario: Navigation — "Users" sits between Articles and Integration
Given the user is on /users
When DashboardShell mounts
Then the sidebar and the mobile drawer list Home, Articles, Users, Integration, Settings in that order
And "Users" has the users icon, links to /users and has aria-current="page"
Scenario: Loading — skeleton rows after 150 ms while the first request, or a retry, is in flight
Given GET /v1/user/ has not yet resolved
When the user navigates to /users
Then nothing is drawn in place of the list for the first 150 ms
And after 150 ms 5 skeleton rows replace the list, on desktop each with one bar per column
plus a RoleBadge and an InviteStatusBadge placeholder and below md in the board's two-bar
card shape, and the list container is aria-busy="true"
When GET /v1/user/ then resolves 200 with the Default fixture
Then the skeleton rows are replaced by the Default state's rows
Scenario: Only you — nobody has been invited yet
Given GET /v1/user/ resolves 200 with only user id 1 "marta" (email "marta@renew.example",
role "owner"), accepted 12 Mar 2026, and the session user is "marta" with role "owner"
When the user navigates to /users
Then the list has one row: "marta@renew.example" with the "you" tag, "—", "owner", an
Accepted badge and "12 Mar 2026"
And under the list the hint reads "Invite someone so they can sign in with their own account
instead of sharing yours."
And "Invite user" is still available
Scenario: Display names in the Users list — saved names show, empty ones show a dash
Given GET /v1/auth/me resolves 200 for user id 1 with display_name "Marta Alves" and role "owner"
And GET /v1/user/ resolves 200 with the Default fixture where user id 1 has display_name
"Marta Alves"
When the user navigates to /users
Then the row "marta@renew.example" (you) shows "Marta Alves", "owner" and an Accepted badge
And the row "ines.duarte@renew.example" shows "Inès Duarte", "admin" and an Accepted badge
And the row "jonas@renew.example" shows a muted "—", "admin" and an Accepted badge
And the sidebar chip also shows "Marta Alves"
Scenario Outline: Non-owners cannot invite — "Invite user" and the hint are not rendered
Given the session user is "<username>" with role "<role>" and GET /v1/user/ resolves 200
with <fixture>
When the user navigates to /users at desktop and at a below-md width
Then <invite>
And the list still renders normally
And <hint>
Examples:
| username | role | fixture | invite | hint |
| jonas | admin | the Default fixture | no "Invite user" button is rendered, header or pinned | the pinned button's space is not reserved |
| jonas | admin | only user id 1 "marta" and user id 2 "jonas" | no "Invite user" button is rendered, header or pinned | the "Invite someone…" hint is not shown |
| marta | owner | the Default fixture | "Invite user" is rendered in the header (desktop) and pinned (below md) | the list is unchanged |
Scenario: An unknown or missing role is treated as non-owner
Given GET /v1/auth/me resolves 200 without a role
When the user navigates to /users
Then no "Invite user" button is rendered
Scenario Outline: Error — a 500 or a network failure replaces the list with an alert and a retry
Given GET /v1/user/ <failure>
When the user navigates to /users
Then an error alert with no close button shows the title "Couldn't load users" and the text
"Check your connection and try again.", with an action "Try again" (icon rotate-cw)
And no table or cards are shown
When the user activates "Try again"
Then the Loading state shows and GET /v1/user/ is sent again
When it then resolves 200 with the Default fixture
Then the Default state's rows replace the alert
Examples:
| failure |
| resolves with a 500 response |
| never reaches the server |
Scenario: Invite: default — opening the modal
Given the Default state has loaded
When the user activates "Invite user"
Then InviteUserModal opens with title "Invite a user" and the text "We'll email them a link to
choose a username and password. The link expires after 3 days."
And the Email field is empty, focused, with placeholder "name@example.com"
And "Cancel" and "Send invite" are present, and nothing has been sent
And the list stays visible behind the modal, and below md the pinned "Invite user" button is hidden
Scenario Outline: Invite: validation — an invalid address is refused before any request
Given the modal is open
When the user types "<value>" into Email and <trigger>
Then the field shows the error "Enter a full email address, like name@example.com."
And POST /v1/user/invite is never sent
Examples:
| value | trigger |
| sam.oliveira@renew | moves focus away |
| not-an-email | activates "Send invite" |
| | activates "Send invite" |
Scenario: Invite: validation — the error clears as soon as the address is fixed
Given the modal shows the Email error for "sam.oliveira@renew"
When the user changes the value to "sam.oliveira@renew.example"
Then the error disappears
Scenario: Invite: sending — the form is locked and cannot be dismissed
Given the modal is open with Email "lea.martin@renew.example"
When the user activates "Send invite"
Then POST /v1/user/invite is sent with JSON {"email": "lea.martin@renew.example"}
And the Email field and "Cancel" are disabled and the confirm button reads "Sending…" with a
loading indicator
And pressing Esc or clicking the backdrop does not close the modal
Scenario: Invite sent — a 201 closes the modal, adds a Pending row on top and raises a toast
Given the Default state has loaded, and the modal is open with Email "lea.martin@renew.example"
with "Send invite" activated
When POST /v1/user/invite resolves 201 with id 3, kind "invite", email
"lea.martin@renew.example", status "pending", created_at now, expires_at 3 days later
Then the modal closes and focus returns to "Invite user"
And GET /v1/user/ is not called again
And the list has 6 rows, the first being "lea.martin@renew.example" with "—", "admin", a
Pending badge and "Today", drawn with the --ui-bg-elevated background
And the other 5 rows are unchanged and follow it in their previous order
And a toast appears: color success, icon i-lucide-circle-check, id "invite-sent-3", title
"Invite sent", description "lea.martin@renew.example has 3 days to accept."
Scenario: Invite sent to an address whose invite had expired replaces the old row
Given the Default state has loaded, with the Expired row "p.huber@gmail.com"
When the user invites "p.huber@gmail.com" and POST /v1/user/invite resolves 201
Then the list holds exactly one row for "p.huber@gmail.com", first, with a Pending badge
And the Expired row is gone
Scenario: Invite sent into the Only-you state keeps a coherent list
Given the Only-you state has loaded
When an invite for "lea.martin@renew.example" is sent and resolves 201
Then the list shows the new Pending row above the "marta@renew.example" row
And the Only-you hint is no longer shown
Scenario Outline: Invite: already a user (409) — the field error depends on the response text
Given the modal is open with Email "<email>", and "Send invite" has been activated
When POST /v1/user/invite resolves 409 with body "<body>"
Then the modal re-enables, keeping "<email>" in the field
And the field shows the error "<error>"
And no request-failure alert is shown
Examples:
| email | body | error |
| jonas@renew.example | This address already has an account. | This address already has an account. |
| sam.oliveira@renew.example | There's already a pending invite for this address. | There's already a pending invite for this address. |
Scenario: A 400 that got past this form's own check
Given the modal is open with Email "lea.martin@renew.example", and "Send invite" has been activated
When POST /v1/user/invite resolves 400
Then the modal re-enables, keeping the address
And the field shows "Enter a full email address, like name@example.com."
And an alert reads "Something in the form isn't valid. Check the highlighted fields."
Scenario: Invite: rate limited — a 429 shows a dialog alert and keeps the address
Given the modal is open with Email "lea.martin@renew.example", and "Send invite" has been activated
When POST /v1/user/invite resolves 429 with body apperr.TooManyRequestsErrorMessage
Then the modal re-enables, keeping "lea.martin@renew.example" in the field
And an alert above the buttons reads "Too many invites. Wait a moment, then try again."
And the field shows no error
And the list is unchanged
When the user activates "Send invite" again and POST /v1/user/invite resolves 201
Then the modal closes, the Pending row appears on top and the "Invite sent" toast is raised
Scenario Outline: Invite: failed — a 500 or a network failure keeps the address and offers a retry
Given the modal is open with Email "lea.martin@renew.example", and "Send invite" has been activated
When POST /v1/user/invite <failure>
Then the modal re-enables, keeping "lea.martin@renew.example" in the field
And an alert above the buttons reads "Couldn't send the invite. Try again in a moment."
And the field shows no error
And the list is unchanged
Examples:
| failure |
| resolves with a 500 response |
| resolves with a 500 response whose body is "Couldn't send the invite. Try again in a moment." |
| never reaches the server |
Scenario: Retrying after a failure succeeds
Given the modal shows the failed alert for "lea.martin@renew.example"
When the user activates "Send invite" again
Then POST /v1/user/invite is sent again with the same JSON body
When it resolves 201
Then the modal closes, the Pending row appears on top and the "Invite sent" toast is raised
Scenario: Cancel discards the address with no confirmation
Given the modal is open with Email "lea.martin@renew.example"
When the user activates "Cancel"
Then the modal closes immediately, with no confirmation prompt, and no request is sent
And reopening the modal shows an empty Email field in its default state
+144
View File
@@ -0,0 +1,144 @@
# QA: Users screen and InviteUserModal
## Implementation note for coder (informational, not a QA assertion)
The invitations API is already built and covered by features/invitations.qa.md: this slice has no
Go change in this slice; the API shape was extended by user_roles.feature, so it has no HTTP-level Go section.
The shell specs were amended to five destinations (Home, Articles, Users, Integration, Settings):
nuxt_ui_shell_foundation.feature / .qa.md (case 14) and dashboard_shell_branding.feature. Their
Vitest tests must be updated in the same change.
The Invite sent toast uses `useToast().add({ id: 'invite-sent-{id}', color: 'success', icon:
'i-lucide-circle-check', title: 'Invite sent', description: '{email} has 3 days to accept.' })`.
The list items are keyed by `kind` and `id`.
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi`'s `request` for `GET /v1/user/` and `POST /v1/user/invite` per case; no real backend.
Mount UsersPage inside DashboardShell with a resolved verified session (id 1, username "marta",
role "owner") and a test router at /users; cases 6 to 17 use that owner session. The Default
fixture is the Background's 5 items; the invite fixture is
id 3, email "lea.martin@renew.example". No test freezes the system date. The specs only assert on
the fixture's absolute dates; the sent row's "Today" label is not asserted anywhere (see the Visual
part). Run each layout case at a desktop and a below-md width (mock `matchMedia`).
1. **Default** — assert breadcrumb "Users", title, subtitle, "Invite user", the table header
labels (Email, Display name, Role, Invite status, Created), rows in fixture order, per row the
email, the display name or "—", the RoleBadge word and class (owner filled, admin outlined),
the badge word and the absolute date, "Paul Huber" on the invite row, the "you" tag only on
"marta@renew.example", no username text in any row, and the below-md cards (display name line
only when set).
2. **Navigation** — assert the sidebar and the drawer list Home, Articles, Users, Integration,
Settings in that order, and "Users" carries aria-current="page" on /users.
3. **Loading** — unresolved `GET`; with fake timers assert nothing is drawn at 149 ms; at 150 ms
assert 5 skeleton rows and `aria-busy="true"`, and at desktop that each row has a RoleBadge
and a status badge placeholder (below md the cards keep the two-bar shape); resolve and
assert the Default rows.
4. **Only you** — a single "marta" item (email, role "owner"); assert the row, the hint text and
"Invite user".
5. **Error, Examples-driven** — reject with `ApiError(500)`, then `NetworkError`; assert the alert
copy, the "Try again" action, no close button and no rows; click "Try again"; assert `request`
is called again, then resolve the Default fixture and assert its rows.
6. **Invite: default** — click "Invite user"; assert title, text, an empty focused Email with its
placeholder, "Cancel", "Send invite"; below md assert the pinned button is hidden while open.
7. **Invite: validation, Examples-driven** — "sam.oliveira@renew" then blur; "not-an-email" then
submit; empty then submit; assert the field error, no `request` call, and focus on the field.
Assert that fixing the value clears the error.
8. **Invite: sending** — valid address, submit; assert one `POST /v1/user/invite` with body
`{"email":"lea.martin@renew.example"}`, the field and "Cancel" disabled, "Sending…", and
Escape and backdrop click not closing the modal.
9. **Invite sent** — resolve 201 with the invite fixture; assert the modal closes, `GET /v1/user/`
was not called a second time, the list has 6 rows with the new Pending row first and the
others unchanged, the first row has the `--ui-bg-elevated` background class, and the toast
was raised with id "invite-sent-3", color success, icon "i-lucide-circle-check", title
"Invite sent" and description "lea.martin@renew.example has 3 days to accept." Assert the new
first row shows "—" and "admin", and nothing about the "Today" label.
10. **Replacement of an expired invite** — invite "p.huber@gmail.com", resolve 201; assert exactly
one row for that address, first and Pending.
11. **Invite sent into Only you** — assert the new row above "marta" and the hint gone.
12. **409, Examples-driven** — reject with `ApiError(409)` carrying each of the two texts; assert
the matching field error, the address kept, no alert. Also assert an unknown 409 body falls
back to "This address already has an account.".
13. **400 got through** — reject with `ApiError(400)`; assert the alert and the field error.
14. **Rate limited (429)** — reject with `ApiError(429)` carrying `apperr.TooManyRequestsErrorMessage`
as body; assert the alert "Too many invites. Wait a moment, then try again." above the buttons
(the raw body is not shown), the address kept, the form re-enabled, no field error and the
list unchanged; submit again, resolve 201, and assert the closed modal, the row and the toast.
15. **Failed, Examples-driven** — `ApiError(500)`, `ApiError(500)` with the API's own text as body,
`NetworkError`; assert the alert "Couldn't send the invite. Try again in a moment." (shown
once, not the raw body), the address kept, no field error, the list unchanged.
16. **Retry after failure** — from 15, submit again; assert `request` is called a second time with
the same body; resolve 201 and assert the closed modal, the row and the toast.
17. **Cancel discards** — type, click "Cancel"; assert immediate close, no `request`, an empty
field on reopening, and focus back on the opening button.
18. **Display names in the Users list** — the Default fixture with user 1 named "Marta Alves"
(session `/v1/auth/me` too); assert the "marta@renew.example" row shows "Marta Alves", "owner"
and Accepted, the "ines.duarte@renew.example" row "Inès Duarte" and "admin", the
"jonas@renew.example" row "—" and "admin", and the sidebar chip "Marta Alves".
19. **Non-owners, Examples-driven** — session role "admin", at desktop and below md; assert no
"Invite user" button (header or pinned), the list still renders, no reserved space for the
pinned button, and the hint absent for a list of only "marta" and "jonas". Also a session with
no role (no button) and an owner control (button present in both layouts).
## Visual (task visual:check -- users, desktop and mobile, light and dark)
Reference: `docs/design/screens/users.md`, board group "Users" in `docs/design/source/RenewCMS
Screens Back-office.dc.html`, exact values in `docs/design/source/AppFrame.dc.html`. Add each
state's mock to `web/visual/states.ts` with the board's own sample data. The gate is hard: every
capture of every non-skipped state must be within 10 %, for both viewports and both themes.
- [ ] Fixtures: `usersFixture` in `web/visual/states.ts` follows the board data: invite 2
`sam.oliveira@renew.example` pending, no name; invite 1 `p.huber@gmail.com` with
`display_name: 'Paul Huber'` expired; user 3 `ines.duarte@renew.example` "Inès Duarte" admin;
user 2 `jonas@renew.example` admin, empty name; user 1 `marta@renew.example` owner, empty
name. `verifiedSession` carries `role: 'owner'`. `profileSession` and `usersWithDisplayNames`
are updated so "Display names in the Users list" shows "Marta Alves", owner.
- [ ] Default: the 5 board rows by email with display names, roles and status badges, dates
27 Sep 2026, 3 Aug 2026, 18 Jun 2026, 2 Apr 2026, 12 Mar 2026; session user `marta`. The
Cancel/Renew buttons in the sixth column are specified in features/users_row_actions.feature.
- [ ] Loading: 5 skeleton rows, with role and status placeholders on desktop and the board's
two-bar cards on mobile; the setup must give skeletons time to show (150 ms) before the
capture.
- [ ] Only you: the single `marta@renew.example` row (owner) plus the hint.
- [ ] Profile "Display names in the Users list" (`task visual:check -- profile "Display names in
the Users list"`): Marta Alves / Inès Duarte / dash.
- [ ] Not drawn, no visual state: non-owner rendering (no "Invite user", no hint). Covered by
Vitest only (case 19); do not add it to `web/visual/states.ts`.
- [ ] Error: the alert and "Try again", no table or cards; the header button is still drawn.
- [ ] Invite: default: modal over the Default list, empty focused Email; the mobile pinned button hidden.
- [ ] Invite: validation: value `sam.oliveira@renew`, error copy.
- [ ] Invite: sending: value `lea.martin@renew.example`, disabled field, "Sending…".
- [ ] Invite: already a user (409): value `jonas@renew.example`, error "This address already has an account.".
- [ ] Invite: failed: value `lea.martin@renew.example`, alert "Couldn't send the invite. Try again in a moment.".
- [ ] skip: clock-sensitive. Invite sent: `skip: 'clock-sensitive'` in `web/visual/states.ts`
("Today"). It prints SKIP, and is never investigated or date-frozen. Its Vitest coverage is case 9.
- [ ] Not drawn, no visual state: the pending-invite 409 variant and the 429 alert. They are
covered by Vitest only (cases 12 and 14); do not add them to `web/visual/states.ts`.
- [ ] Layout, taken from the board frame (`AppFrame.dc.html`), not `components.md`: desktop header
row is title block left and the 32 px "Invite user" button right, aligned to the bottom of
the row; on mobile the button is 16 px from left, right and bottom, 48 px high, 18 px icon.
- [ ] Layout, from `AppFrame.dc.html`: 36 px table header, 48 px rows, sixth 150 px track empty;
RoleBadge 20 px high, 7 px side padding, IBM Plex Mono 11 px medium; cards show the email
line, then the display name, then the badges line.
- [ ] Not covered by screenshots: keyboard and focus order (Tab reaches "Invite user", the modal
focus starts on Email, then Cancel, then "Send invite", focus is trapped, Esc closes it in
every dismissible state and is blocked while Sending, focus returns to the opening button);
hover and active on the buttons; motion (240 ms modal, skeleton pulse 1.6 s, both stopped
under reduced motion).
## Manual verification
- **Real round trips against `task dev`** — Vitest only mocks `useApi`. Invite a real address and
confirm: the 201 row, the 409 texts for an existing account and a live pending invite, the
replacement of an expired invite, the 429 after exceeding `AUTH_RATE_LIMIT_MAX_ATTEMPTS` within
`AUTH_RATE_LIMIT_WINDOW_SECONDS`, and the list order after a reload.
- **Real invitation email** — needs real or sandboxed SMTP (`SMTP_HOST` and the related env
vars): the mail arrives and its link `{PUBLIC_URL}/invite/accept?c=...` carries the code. The
link will not resolve in the SPA, because the accept screen is out of scope.
- **Admin session** — sign in once as an admin against `task dev` and confirm there is no
"Invite user" button and no "Only you" hint.
- **Toast placement and stacking on a live app** — bottom right on desktop and above the pinned
button on mobile.
- **"Today" and the elevated row on a live app** — confirm the new row and the "Today" label
against the real clock, since visual:check skips this state.
+44
View File
@@ -0,0 +1,44 @@
package invite
import (
"errors"
"time"
)
var ErrEmailHasAccount = errors.New("email already has an account")
var ErrPendingInvite = errors.New("pending invite already exists")
var ErrInviteNotFound = errors.New("invite not found")
var ErrInviteEmailNotSent = errors.New("invite email not sent")
var ErrInviteInvalid = errors.New("invite invalid")
var ErrInviteExpired = errors.New("invite expired")
var ErrInviteAlreadyAccepted = errors.New("invite already accepted")
const Lifetime = 3 * 24 * time.Hour
type Status string
const (
StatusPending Status = "pending"
StatusExpired Status = "expired"
StatusAccepted Status = "accepted"
)
type Invite struct {
ID uint32 `json:"id"`
Email string `json:"email"`
HashedCode string `json:"hashed_code"`
ExpiresAt time.Time `json:"expires_at"`
InvitedBy uint32 `json:"invited_by"`
AcceptedAt *time.Time `json:"accepted_at"`
CreatedAt time.Time `json:"created_at"`
}
func (i Invite) StatusAt(now time.Time) Status {
if i.AcceptedAt != nil {
return StatusAccepted
}
if i.ExpiresAt.After(now) {
return StatusPending
}
return StatusExpired
}
@@ -0,0 +1,14 @@
package invite
import (
"RenewCMS/internal/domain/user"
"time"
)
type Repository interface {
Create(invite Invite) (Invite, error)
GetAll() []Invite
Delete(id uint32) error
Renew(id uint32, hashedCode string, expiresAt time.Time, createdAt time.Time) (Invite, error)
AcceptWithUser(inviteID uint32, acceptedAt time.Time, newUser user.User) (user.User, error)
}
@@ -0,0 +1,5 @@
package settings
type Settings struct {
Version string `json:"version"`
}
+11
View File
@@ -13,6 +13,15 @@ var ErrVerificationCodeExpired = errors.New("verification code expired")
var ErrAlreadyVerified = errors.New("user already verified")
var ErrInvalidPasswordResetCode = errors.New("invalid password reset code")
var ErrPasswordResetCodeExpired = errors.New("password reset code expired")
var ErrInvalidDisplayName = errors.New("invalid display name")
var ErrUsernameTaken = errors.New("username taken")
type Role string
const (
RoleOwner Role = "owner"
RoleAdmin Role = "admin"
)
type User struct {
ID uint32 `json:"id"`
@@ -20,7 +29,9 @@ type User struct {
Password string `json:"password"`
PasswordResetCode string `json:"password_reset_code"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
IsVerified bool `json:"is_verified"`
Role Role `json:"role"`
VerificationCode string `json:"verification_code"`
VerificationExpiration time.Time `json:"verification_expiration"`
PasswordResetExpiration time.Time `json:"password_reset_expiration"`
@@ -14,4 +14,5 @@ type Repository interface {
UpdatePasswordResetCode(userId uint32, code string, expiration time.Time) (User, error)
ClearVerificationCode(userId uint32) (User, error)
ResetPassword(userId uint32, hashedPassword string) (User, error)
UpdateDisplayName(userId uint32, displayName string) (User, error)
}
@@ -31,6 +31,7 @@ type Settings struct {
Smtp SmtpSettings
AuthRateLimit AuthRateLimitSettings
TrustedProxies []string
Version string
}
func (s Settings) IsProduction() bool {
@@ -24,14 +24,25 @@ func NewMailRepository(smtp config.SmtpSettings) *MailRepository {
const defaultSubject = "RenewCMS | Action required"
func (m MailRepository) Render(templateName string, data any) (string, string, error) {
subject := defaultSubject
type subjectProvider interface {
Subject() string
}
func subjectFor(templateName string, data any) string {
if provider, ok := data.(subjectProvider); ok {
return provider.Subject()
}
switch templateName {
case "verification":
subject = "Verify your RenewCMS account"
return "Verify your RenewCMS account"
case "password-reset":
subject = "Reset your RenewCMS password"
return "Reset your RenewCMS password"
}
return defaultSubject
}
func (m MailRepository) Render(templateName string, data any) (string, string, error) {
subject := subjectFor(templateName, data)
tmpl, err := template.ParseFS(mailTemplateFiles, "templates/"+templateName+".html")
if err != nil {
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<meta name="supported-color-schemes" content="light dark">
<title>You're invited to RenewCMS</title>
<style>
body { margin: 0; padding: 0; width: 100%; -webkit-text-size-adjust: 100%; }
table { border-collapse: collapse; }
a { color: #111111; }
@media (max-width: 620px) {
.rc-card { padding: 28px 20px !important; }
.rc-btn a { display: block !important; }
}
@media (prefers-color-scheme: dark) {
.rc-bg { background-color: #0a0a0a !important; }
.rc-card { background-color: #111111 !important; border-color: #333333 !important; }
.rc-h1, .rc-word { color: #fafafa !important; }
.rc-text { color: #e6e4e0 !important; }
.rc-muted { color: #999999 !important; }
.rc-mark { border: 1px solid #444444 !important; }
.rc-btn td { background-color: #fafafa !important; }
.rc-btn a { background-color: #fafafa !important; color: #111111 !important; border-color: #fafafa !important; }
.rc-url { color: #e6e4e0 !important; background-color: #1a1a1a !important; }
.rc-rule { border-color: #333333 !important; }
}
</style>
</head>
<body class="rc-bg" style="margin:0;padding:0;background-color:#fafafa;">
<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;">{{.InvitedBy}} invited you to work on articles in RenewCMS. The invite expires in 3 days.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="rc-bg" style="background-color:#fafafa;">
<tr>
<td align="center" style="padding:40px 12px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;">
<tr>
<td style="padding:0 0 20px 0;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="rc-mark" width="32" height="32" align="center" valign="middle" bgcolor="#111111" style="width:32px;height:32px;background-color:#111111;color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:19px;font-weight:bold;line-height:32px;">R</td>
<td class="rc-word" style="padding-left:10px;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:17px;font-weight:600;color:#111111;">RenewCMS</td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="rc-card" style="background-color:#ffffff;border:1px solid #e6e4e0;padding:40px;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;">
<h1 class="rc-h1" style="margin:0 0 16px 0;font-size:24px;line-height:32px;font-weight:600;color:#111111;">You're invited to RenewCMS</h1>
<p class="rc-text" style="margin:0 0 28px 0;font-size:16px;line-height:26px;color:#222222;">{{.InvitedBy}} invited you to write and publish articles in RenewCMS at {{.Host}}. Accept to choose a username and password. You'll sign in with your own account.</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" class="rc-btn">
<tr>
<td bgcolor="#111111" style="background-color:#111111;">
<a href="{{.Host}}/invite/accept?c={{.VerificationCode}}" target="_blank" style="display:inline-block;padding:14px 24px;border:1px solid #111111;background-color:#111111;color:#ffffff;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:16px;font-weight:600;line-height:20px;text-decoration:none;text-align:center;">Accept invite</a>
</td>
</tr>
</table>
<p class="rc-muted" style="margin:16px 0 0 0;font-size:14px;line-height:22px;color:#666666;">This invite was sent to {{.Email}}. It expires in 3 days and works once.</p>
<p class="rc-muted" style="margin:28px 0 8px 0;font-size:14px;line-height:22px;color:#666666;">If the button doesn't work, copy this address into your browser:</p>
<p class="rc-url" style="margin:0;padding:10px 12px;background-color:#f3f2f0;font-family:'IBM Plex Mono',Menlo,Consolas,monospace;font-size:13px;line-height:20px;color:#222222;word-break:break-all;">{{.Host}}/invite/accept?c={{.VerificationCode}}</p>
<p class="rc-text rc-rule" style="margin:28px 0 0 0;padding-top:20px;border-top:1px solid #e6e4e0;font-size:14px;line-height:22px;color:#222222;">Not expecting this? Ignore this email and no account will be created. If the invite has expired, ask {{.InvitedBy}} to send a new one.</p>
</td>
</tr>
<tr>
<td class="rc-muted" style="padding:20px 0 0 0;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:12px;line-height:18px;color:#666666;">RenewCMS · {{.Host}}</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
@@ -0,0 +1,30 @@
package mappers
import (
"RenewCMS/internal/domain/invite"
"RenewCMS/internal/infrastructure/persistence/models"
)
func InviteToDomain(m models.Invite) invite.Invite {
return invite.Invite{
ID: m.ID,
Email: m.Email,
HashedCode: m.HashedCode,
ExpiresAt: m.ExpiresAt,
InvitedBy: m.InvitedBy,
AcceptedAt: m.AcceptedAt,
CreatedAt: m.CreatedAt,
}
}
func InviteToModel(i invite.Invite) models.Invite {
return models.Invite{
ID: i.ID,
Email: i.Email,
HashedCode: i.HashedCode,
ExpiresAt: i.ExpiresAt,
InvitedBy: i.InvitedBy,
AcceptedAt: i.AcceptedAt,
CreatedAt: i.CreatedAt,
}
}
@@ -26,7 +26,9 @@ func UserToDomain(m models.User) user.User {
Password: m.Password,
PasswordResetCode: nullableStringToDomain(m.PasswordResetCode),
Email: m.Email,
DisplayName: m.DisplayName,
IsVerified: m.IsVerified,
Role: user.Role(m.Role),
VerificationCode: nullableStringToDomain(m.VerificationCode),
VerificationExpiration: m.VerificationExpiration,
PasswordResetExpiration: m.PasswordResetExpiration,
@@ -42,7 +44,9 @@ func UserToModel(a user.User) models.User {
Password: a.Password,
PasswordResetCode: DomainToNullableString(a.PasswordResetCode),
Email: a.Email,
DisplayName: a.DisplayName,
IsVerified: a.IsVerified,
Role: string(a.Role),
VerificationCode: DomainToNullableString(a.VerificationCode),
VerificationExpiration: a.VerificationExpiration,
PasswordResetExpiration: a.PasswordResetExpiration,
@@ -0,0 +1,13 @@
package models
import "time"
type Invite struct {
ID uint32 `gorm:"primaryKey;autoIncrement"`
Email string `gorm:"index;not null"`
HashedCode string `gorm:"not null"`
ExpiresAt time.Time
InvitedBy uint32 `gorm:"not null"`
AcceptedAt *time.Time
CreatedAt time.Time `gorm:"autoCreateTime"`
}
@@ -10,7 +10,9 @@ type User struct {
Password string `gorm:"not null"`
PasswordResetCode *string `gorm:"unique"`
Email string `gorm:"unique;not null"`
DisplayName string `gorm:"not null;default:''"`
IsVerified bool `gorm:"default=false;not null"`
Role string `gorm:"not null;default:''"`
VerificationCode *string `gorm:"unique"`
VerificationExpiration time.Time
PasswordResetExpiration time.Time
@@ -0,0 +1,85 @@
package persistence
import (
domainInvite "RenewCMS/internal/domain/invite"
domainUser "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/persistence/mappers"
entity "RenewCMS/internal/infrastructure/persistence/models"
"time"
"gorm.io/gorm"
)
type InviteRepository struct {
db *gorm.DB
}
func NewInviteRepository(db *gorm.DB) *InviteRepository {
return &InviteRepository{db}
}
func (i *InviteRepository) Create(invite domainInvite.Invite) (domainInvite.Invite, error) {
model := mappers.InviteToModel(invite)
model.ID = 0
if err := i.db.Create(&model).Error; err != nil {
return domainInvite.Invite{}, err
}
return mappers.InviteToDomain(model), nil
}
func (i *InviteRepository) GetAll() []domainInvite.Invite {
var invites []entity.Invite
i.db.Model(&entity.Invite{}).Find(&invites)
var domainInvites []domainInvite.Invite
for _, localInvite := range invites {
domainInvites = append(domainInvites, mappers.InviteToDomain(localInvite))
}
return domainInvites
}
func (i *InviteRepository) Delete(id uint32) error {
result := i.db.Delete(&entity.Invite{}, id)
return deleteOrNotFound(result, domainInvite.ErrInviteNotFound)
}
func (i *InviteRepository) Renew(id uint32, hashedCode string, expiresAt time.Time, createdAt time.Time) (domainInvite.Invite, error) {
result := i.db.Model(&entity.Invite{}).
Where("id = ? AND accepted_at IS NULL", id).
Updates(map[string]any{
"hashed_code": hashedCode,
"expires_at": expiresAt,
"created_at": createdAt,
})
if err := deleteOrNotFound(result, domainInvite.ErrInviteNotFound); err != nil {
return domainInvite.Invite{}, err
}
var model entity.Invite
if err := i.db.First(&model, id).Error; err != nil {
return domainInvite.Invite{}, err
}
return mappers.InviteToDomain(model), nil
}
func (i *InviteRepository) AcceptWithUser(inviteID uint32, acceptedAt time.Time, newUser domainUser.User) (domainUser.User, error) {
createdModel := mappers.UserToModel(newUser)
err := i.db.Transaction(func(tx *gorm.DB) error {
marked := tx.Model(&entity.Invite{}).
Where("id = ? AND accepted_at IS NULL", inviteID).
Update("accepted_at", acceptedAt)
if err := deleteOrNotFound(marked, domainInvite.ErrInviteNotFound); err != nil {
return err
}
return tx.Create(&createdModel).Error
})
if err != nil {
return domainUser.User{}, err
}
return mappers.UserToDomain(createdModel), nil
}
var _ domainInvite.Repository = &InviteRepository{}
@@ -33,6 +33,8 @@ func (u *UserRepository) Create(user domainUser.User) (domainUser.User, error) {
Password: user.Password,
PasswordResetCode: mappers.DomainToNullableString(user.PasswordResetCode),
Email: user.Email,
IsVerified: user.IsVerified,
Role: string(user.Role),
VerificationCode: mappers.DomainToNullableString(user.VerificationCode),
VerificationExpiration: user.VerificationExpiration,
})
@@ -48,7 +50,7 @@ func (u *UserRepository) Create(user domainUser.User) (domainUser.User, error) {
}
func (u *UserRepository) Delete(id uint32) error {
result := u.db.Delete(&domainUser.User{}, id)
result := u.db.Delete(&entity.User{}, id)
return deleteOrNotFound(result, domainUser.ErrUserNotFound)
}
@@ -169,4 +171,20 @@ func (u *UserRepository) ResetPassword(userId uint32, hashedPassword string) (do
return mappers.UserToDomain(localUser), nil
}
func (u *UserRepository) UpdateDisplayName(userId uint32, displayName string) (domainUser.User, error) {
var localUser entity.User
err := u.db.Model(&entity.User{}).First(&localUser, userId).Error
if err != nil {
return domainUser.User{}, mapNotFoundErr(err, domainUser.ErrUserNotFound)
}
localUser.DisplayName = displayName
err = u.db.Save(&localUser).Error
if err != nil {
return domainUser.User{}, err
}
return mappers.UserToDomain(localUser), nil
}
var _ domainUser.Repository = &UserRepository{}
@@ -0,0 +1,33 @@
package persistence
import (
domainUser "RenewCMS/internal/domain/user"
entity "RenewCMS/internal/infrastructure/persistence/models"
"gorm.io/gorm"
)
func BackfillUserRoles(db *gorm.DB) error {
return db.Transaction(func(tx *gorm.DB) error {
var firstUser entity.User
result := tx.Where("role = ''").Order("id asc").Limit(1).Find(&firstUser)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return nil
}
var lowest entity.User
if err := tx.Order("id asc").First(&lowest).Error; err != nil {
return err
}
if lowest.Role == "" {
if err := tx.Model(&entity.User{}).Where("id = ?", lowest.ID).Update("role", string(domainUser.RoleOwner)).Error; err != nil {
return err
}
}
return tx.Model(&entity.User{}).Where("role = ''").Update("role", string(domainUser.RoleAdmin)).Error
})
}
@@ -0,0 +1,87 @@
package useCases
import (
"RenewCMS/internal/domain/hash"
"RenewCMS/internal/domain/invite"
"RenewCMS/internal/domain/user"
"errors"
"strings"
"time"
)
type AcceptInviteUseCase struct {
userRepository user.Repository
inviteRepository invite.Repository
hasher hash.Hasher
}
type AcceptInviteCommand struct {
Code string
Username string
Password string
}
func NewAcceptInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher) *AcceptInviteUseCase {
return &AcceptInviteUseCase{userRepository, inviteRepository, hasher}
}
func (a *AcceptInviteUseCase) AcceptInvite(command AcceptInviteCommand) (user.User, error) {
now := time.Now()
pending, err := findUsableInvite(a.inviteRepository, a.hasher, command.Code, now)
if err != nil {
return user.User{}, err
}
if a.emailHasAccount(pending.Email) {
if _, err := findUsableInvite(a.inviteRepository, a.hasher, command.Code, now); err != nil {
return user.User{}, err
}
return user.User{}, invite.ErrEmailHasAccount
}
if err := a.ensureUsernameFree(command.Username); err != nil {
return user.User{}, err
}
hashedPassword, err := a.hasher.Hash(command.Password)
if err != nil {
return user.User{}, err
}
createdUser, err := a.inviteRepository.AcceptWithUser(pending.ID, now, user.User{
Username: command.Username,
Password: hashedPassword,
Email: pending.Email,
IsVerified: true,
Role: user.RoleAdmin,
})
if errors.Is(err, invite.ErrInviteNotFound) {
return user.User{}, invite.ErrInviteInvalid
}
if err != nil {
return user.User{}, err
}
return createdUser, nil
}
func (a *AcceptInviteUseCase) emailHasAccount(email string) bool {
for _, existingUser := range a.userRepository.GetAll() {
if strings.EqualFold(existingUser.Email, email) {
return true
}
}
return false
}
func (a *AcceptInviteUseCase) ensureUsernameFree(username string) error {
_, err := a.userRepository.GetByUsername(username)
if err == nil {
return user.ErrUsernameTaken
}
if errors.Is(err, user.ErrUserNotFound) {
return nil
}
return err
}
@@ -0,0 +1,18 @@
package useCases
import "RenewCMS/internal/domain/invite"
type CancelInviteUseCase struct {
inviteRepository invite.Repository
}
func NewCancelInviteUseCase(inviteRepository invite.Repository) *CancelInviteUseCase {
return &CancelInviteUseCase{inviteRepository}
}
func (c *CancelInviteUseCase) CancelInvite(id uint32) error {
if _, err := findManageableInvite(c.inviteRepository, id); err != nil {
return err
}
return c.inviteRepository.Delete(id)
}
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff. Show more