password-reset: a confirmed e-mail, then a link to reset the password

Agreed by the owner on 2026-10-13 ("the e-mail must be confirmed");
notifications to an unconfirmed address settled on 2026-10-17: "Без
подтверждения слать". Mockups 2f5f5b2, route guard b7bbb2c, panel guard
0774da2.

Migration 0013: users.email_confirmed_at ('' for every address saved
before it) and user_links - the SHA-256 of a link's token, its user,
purpose (confirm, reset), address, created and expiry. A changed address
loses its mark (keepConfirmed, in UpdateUser and SaveUser).

internal/web/auth/links.go. A link is 256 bits from crypto/rand, mailed as
https://SELFPOST_HOSTNAME/... - never the request's Host. Confirmation:
24 h, sent when an address is saved (Account, or the global role's user
form) and by Account's Send the link again; its page /confirm/<token> has
a button (a GET changes nothing) and confirms only for a session of its
own account. Reset: /login/reset asks for a username and answers the same
for every name (the sign-in page, "If that account has a confirmed e-mail,
the link is on its way"), mailing after the answer; only a confirmed
address gets one, none within ten minutes of the last, five links an hour
per account, five requests in 15 minutes per client address;
/login/reset/<token> (30 min) sets the password with the link taken in
the same transaction that checks the address again
(store.TakeResetLink), then ends every session. Changing the e-mail on
Account asks for the current password. A password set on Account or the
user form removes the reset links; a restore removes every link; the stop
waits for links being mailed (Server.Drain); a rejected request's log line
hides a link's token (loggedPath).

Reviewed for security before the commit (2026-10-17): no high; two
medium and five low, all fixed here - confirming needs the account's
session and the mail does not name the account (a mistyped address was a
takeover); a reset request neither replaces the links already sent nor
spends the account's quota inside ten minutes; take-and-set atomic; the
confirmation mail sent after the answer; the stop waits for mail; a
restore deletes the links; the token kept out of the log.

Tests: store TestUserLinks, TestUserLinkTakenOnce, TestEmailConfirmation,
TestTakeResetLink; auth TestResetSendsALinkOnlyToAConfirmedAddress,
TestResetLinkSetsThePasswordOnce, TestResetLinkDiesWithTheAddress,
TestResetRequestsAreLimited, TestResetRequestsAreSpaced, TestConfirmLink,
TestLinkPathsWithoutAToken; handlers TestAccountEmailIsConfirmedByItsLink,
TestUserFormSendsANewAddressItsLink; web TestLoggedPathHidesTokens; the
view's pages and fixtures; e2e password_reset_by_e_mail runs it through
the sink (and checks a link from before the restore is dead). go vet +
go test (26 packages) and make e2e on the test server for this tree.

Docs: guide § Account, security.md (the bullet and what ends sessions),
architecture (routes), schema-migrations (row 13, users, user_links),
help #account (word for word with the mockup), roadmap row done,
CHANGELOG [Unreleased].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mix
2026-10-17 12:03:27 +03:00
co-authored by Claude Opus 5.5
parent 09edc0fac6
commit b8e156c9f4
43 changed files with 1966 additions and 61 deletions
+78
View File
@@ -4,6 +4,7 @@ import (
"errors"
"net/http"
"strings"
"time"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/validate"
@@ -60,6 +61,11 @@ func (h *Handlers) HandleAccount(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) renderAccount(w http.ResponseWriter, r *http.Request, status int, u store.User, f accountForm) {
page := view.NewAccount(h.shellMeta(r), string(u.Role))
page.Username, page.Email, page.Notify = f.Username, f.Email, f.Notify
var sent time.Time
if l, err := h.store.LatestUserLink(u.ID, store.LinkConfirm, time.Now()); err == nil && l.Email == u.Email {
sent = l.CreatedAt
}
page.WithEmailState(u.Email, !u.EmailConfirmed.IsZero(), sent)
page.WithResult(accountFlash(r), f.Err)
h.view.Render(w, status, "account", page)
}
@@ -68,6 +74,10 @@ func accountFlash(r *http.Request) string {
switch r.URL.Query().Get("done") {
case "profile":
return "Profile saved."
case "profile-link":
return "Profile saved. A link to confirm the new address is on its way."
case "link":
return "A new link is on its way."
case "password":
return "Password changed. Any other signed-in sessions were signed out."
}
@@ -108,6 +118,25 @@ func (h *Handlers) HandleAccountProfile(w http.ResponseWriter, r *http.Request)
fail(http.StatusBadRequest, err.Error())
return
}
// The e-mail is where a reset link goes once it is confirmed, so
// changing it asks for the password, as changing the password does
// (roadmap password-reset; 2.0 security review), on the same limit.
emailChanged := f.Email != u.Email
if emailChanged {
if !h.auth.AllowPasswordChange(u.ID) {
fail(http.StatusTooManyRequests, "Too many attempts. Please wait and try again.")
return
}
current := r.PostFormValue("current_password")
if current == "" {
fail(http.StatusUnauthorized, "Your current password is needed to change the e-mail.")
return
}
if err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(current)); err != nil {
fail(http.StatusUnauthorized, "Current password is incorrect.")
return
}
}
if err := h.store.UpdateUser(u.ID, f.Username, u.PasswordHash, f.Email); err != nil {
if errors.Is(err, store.ErrUserExists) {
fail(http.StatusConflict, "That username is already in use.")
@@ -125,9 +154,54 @@ func (h *Handlers) HandleAccountProfile(w http.ResponseWriter, r *http.Request)
}
}
logf("panel: user %d profile updated (username: %t, e-mail: %t, notifications: %t)", u.ID, f.Username != u.Username, f.Email != u.Email, f.Notify)
if emailChanged && f.Email != "" && h.sendConfirmation(u.ID) {
http.Redirect(w, r, "/account?done=profile-link", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/account?done=profile", http.StatusSeeOther)
}
// HandleAccountConfirmLink sends the account's unconfirmed address its link
// again (Account, "Send the link again").
func (h *Handlers) HandleAccountConfirmLink(w http.ResponseWriter, r *http.Request) {
u, ok := h.accountUser(w, r)
if !ok {
return
}
if u.Email == "" || !u.EmailConfirmed.IsZero() {
http.Redirect(w, r, "/account", http.StatusSeeOther)
return
}
f := formOf(u)
if !h.auth.AllowConfirmationLink(u.ID) {
f.Err = "Too many links asked for. Please wait and try again."
h.renderAccount(w, r, http.StatusTooManyRequests, u, f)
return
}
h.auth.SendConfirmationLater(u)
http.Redirect(w, r, "/account?done=link", http.StatusSeeOther)
}
// sendConfirmation mails the user's unconfirmed address its link after the
// answer, within the limit of links to one address; whether one was sent off.
// A link that cannot go is logged: the address is saved all the same, and
// Account offers to send it again.
func (h *Handlers) sendConfirmation(userID int64) bool {
if h.auth == nil || !h.auth.CanMail() {
return false
}
u, err := h.store.GetUser(userID)
if err != nil || u.Email == "" || !u.EmailConfirmed.IsZero() {
return false
}
if !h.auth.AllowConfirmationLink(u.ID) {
logf("panel: user %d: confirmation links asked for too often; none was sent", u.ID)
return false
}
h.auth.SendConfirmationLater(u)
return true
}
// HandleAccountPassword changes the password. It asks for the current one and
// is rate-limited like a sign-in: the form is a place to guess a password from
// an unattended session.
@@ -178,6 +252,10 @@ func (h *Handlers) HandleAccountPassword(w http.ResponseWriter, r *http.Request)
if token, ok := h.auth.SessionToken(r); ok {
h.auth.DestroyOtherSessions(u.ID, token)
}
// A password set another way leaves no reset link behind it.
if err := h.store.DeleteUserLinks(u.ID, store.LinkReset); err != nil {
logf("panel: account: %v", err)
}
logf("panel: user %d changed their password", u.ID)
http.Redirect(w, r, "/account?done=password", http.StatusSeeOther)
}