feat(api): accept recovery codes as second factor and let users regenerate them

Enabling TOTP returns ten codes that are shown once. Disabling TOTP and
regenerating codes require the password plus a current code.

Closes #40

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 00:35:20 +01:00
1 parent dbea42e7a5
commit 7b063d2cd8
12 files changed
+510 -123

No files matched your search

+102 -34
View File
@@ -37,6 +37,7 @@ type meView struct {
Orgs []orgView `json:"orgs"`
// Set when an org the user belongs to enforces TOTP and the user has none.
TOTPEnrollmentRequired bool `json:"totp_enrollment_required"`
RecoveryCodesLeft int `json:"recovery_codes_left"`
}
func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error) {
@@ -46,11 +47,15 @@ func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error)
if err != nil {
return err
}
left, err := q.CountUnusedRecoveryCodes(ctx, sess.UserID)
if err != nil {
return err
}
orgs, err := q.ListUserOrgs(ctx, sess.UserID)
if err != nil {
return err
}
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}}
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}, RecoveryCodesLeft: int(left)}
for _, o := range orgs {
me.Orgs = append(me.Orgs, orgView{ID: o.ID, Slug: o.Slug, Name: o.Name, IsOwner: o.IsOwner, RequireTOTP: o.RequireTotp})
if o.RequireTotp && !me.TOTP {
@@ -154,32 +159,85 @@ func (s *Server) totpEnable(c *gin.Context) {
return
}
sealedSecret := s.keys.Seal([]byte(secret), sess.UserID[:])
codes := auth.NewRecoveryCodes()
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return q.EnableTOTP(ctx, store.EnableTOTPParams{ID: sess.UserID, TotpSecret: sealedSecret})
if err := q.EnableTOTP(ctx, store.EnableTOTPParams{ID: sess.UserID, TotpSecret: sealedSecret}); err != nil {
return err
}
return replaceRecoveryCodes(ctx, q, sess.UserID, codes)
})
if err != nil {
internalError(c, err)
return
}
_ = s.rdb.Del(ctx, totpSetupKey(sess.UserID)).Err()
c.Status(http.StatusNoContent)
c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
}
type totpDisableRequest struct {
func replaceRecoveryCodes(ctx context.Context, q *store.Queries, user uuid.UUID, codes []string) error {
if err := q.DeleteRecoveryCodes(ctx, user); err != nil {
return err
}
rows := make([]store.InsertRecoveryCodesParams, len(codes))
for i, c := range codes {
rows[i] = store.InsertRecoveryCodesParams{UserID: user, CodeHash: auth.HashRecoveryCode(auth.NormalizeRecoveryCode(c))}
}
_, err := q.InsertRecoveryCodes(ctx, rows)
return err
}
// reauthRequest confirms a sensitive change with the password and a second
// factor, so a hijacked session alone cannot weaken the account.
type reauthRequest struct {
Password string `json:"password" binding:"required,max=1024"`
Code string `json:"code" binding:"required,len=6,numeric"`
Code string `json:"code" binding:"required,max=32"`
}
// reauthenticate checks req for the session user and writes the error
// response itself when it fails.
func (s *Server) reauthenticate(c *gin.Context, req reauthRequest) bool {
ctx := c.Request.Context()
sess := auth.Current(c)
if !s.limit(c, "reauth:"+sess.UserID.String(), 5, 15*time.Minute) {
return false
}
var user store.User
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
user, err = q.GetUser(ctx, sess.UserID)
return err
})
if err != nil {
internalError(c, err)
return false
}
if user.PasswordHash == nil {
fail(c, http.StatusConflict, "no_password")
return false
}
if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok {
invalidCredentials(c)
return false
}
ok, err := s.verifySecondFactor(ctx, sess.UserID, req.Code)
if err != nil {
internalError(c, err)
return false
}
if !ok {
fail(c, http.StatusUnauthorized, "invalid_code")
return false
}
return true
}
func (s *Server) totpDisable(c *gin.Context) {
var req totpDisableRequest
var req reauthRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
sess := auth.Current(c)
if !s.limit(c, "totp_disable:"+sess.UserID.String(), 5, 15*time.Minute) {
return
}
me, err := s.loadMe(ctx, sess)
if err != nil {
internalError(c, err)
@@ -191,33 +249,14 @@ func (s *Server) totpDisable(c *gin.Context) {
return
}
}
var user store.User
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
user, err = q.GetUser(ctx, sess.UserID)
return err
})
if err != nil {
internalError(c, err)
return
}
if user.PasswordHash == nil {
fail(c, http.StatusConflict, "no_password")
return
}
if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok {
invalidCredentials(c)
return
}
if ok, err := s.verifyUserTOTP(ctx, sess.UserID, req.Code); err != nil {
internalError(c, err)
return
} else if !ok {
fail(c, http.StatusUnauthorized, "invalid_code")
if !s.reauthenticate(c, req) {
return
}
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return q.DisableTOTP(ctx, sess.UserID)
if err := q.DisableTOTP(ctx, sess.UserID); err != nil {
return err
}
return q.DeleteRecoveryCodes(ctx, sess.UserID)
})
if err != nil {
internalError(c, err)
@@ -226,9 +265,38 @@ func (s *Server) totpDisable(c *gin.Context) {
c.Status(http.StatusNoContent)
}
func (s *Server) regenerateRecoveryCodes(c *gin.Context) {
var req reauthRequest
if !bind(c, &req) || !s.reauthenticate(c, req) {
return
}
ctx := c.Request.Context()
sess := auth.Current(c)
codes := auth.NewRecoveryCodes()
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return replaceRecoveryCodes(ctx, q, sess.UserID, codes)
})
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
}
var errNoTOTP = errors.New("api: user has no totp")
func (s *Server) verifyUserTOTP(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
// verifySecondFactor accepts a current TOTP code or an unused recovery code,
// which is consumed.
func (s *Server) verifySecondFactor(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
if rc := auth.NormalizeRecoveryCode(code); rc != "" {
var n int64
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
var err error
n, err = q.UseRecoveryCode(ctx, store.UseRecoveryCodeParams{UserID: userID, CodeHash: auth.HashRecoveryCode(rc)})
return err
})
return n == 1, err
}
var user store.User
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
var err error