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

+7 -2
View File
@@ -167,12 +167,17 @@ func (s *Server) login(c *gin.Context) {
s.finishLogin(c, user.ID)
}
// secondFactorRequest carries a TOTP code or a recovery code.
type secondFactorRequest struct {
Code string `json:"code" binding:"required,max=32"`
}
type totpRequest struct {
Code string `json:"code" binding:"required,len=6,numeric"`
}
func (s *Server) loginTOTP(c *gin.Context) {
var req totpRequest
var req secondFactorRequest
if !bind(c, &req) {
return
}
@@ -195,7 +200,7 @@ func (s *Server) loginTOTP(c *gin.Context) {
internalError(c, err)
return
}
ok, err := s.verifyUserTOTP(ctx, userID, req.Code)
ok, err := s.verifySecondFactor(ctx, userID, req.Code)
if err != nil {
internalError(c, err)
return
+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
+6 -5
View File
@@ -165,11 +165,12 @@ func (s *Server) ssoSettingsPage(c *gin.Context) {
func toWebMe(m meView) web.Me {
out := web.Me{
Email: m.Email,
DisplayName: m.DisplayName,
TOTP: m.TOTP,
ActiveOrg: m.ActiveOrg.String(),
TOTPMissing: m.TOTPEnrollmentRequired,
Email: m.Email,
DisplayName: m.DisplayName,
TOTP: m.TOTP,
ActiveOrg: m.ActiveOrg.String(),
TOTPMissing: m.TOTPEnrollmentRequired,
RecoveryCodesLeft: m.RecoveryCodesLeft,
}
for _, o := range m.Orgs {
out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner})
+87
View File
@@ -0,0 +1,87 @@
package api_test
import (
"net/http"
"testing"
"time"
"github.com/pquerna/otp/totp"
)
// enableTOTP turns on TOTP for b and returns the secret and recovery codes.
func (b *browser) enableTOTP() (string, []string) {
b.t.Helper()
st, setup := b.do("POST", "/api/v1/me/totp/setup", nil)
if st != http.StatusOK {
b.t.Fatalf("totp setup = %d %v", st, setup)
}
secret := setup["secret"].(string)
code, _ := totp.GenerateCode(secret, time.Now())
st, body := b.do("POST", "/api/v1/me/totp/enable", map[string]any{"code": code})
if st != http.StatusOK {
b.t.Fatalf("totp enable = %d %v", st, body)
}
var codes []string
for _, c := range body["recovery_codes"].([]any) {
codes = append(codes, c.(string))
}
return secret, codes
}
func TestRecoveryCodes(t *testing.T) {
e := newEnv(t)
email := uniq("r") + "@example.test"
owner := e.browser(t)
owner.signup(email, uniq("rec-"))
_, codes := owner.enableTOTP()
if len(codes) != 10 {
t.Fatalf("enable returned %d recovery codes, want 10", len(codes))
}
login := func(code string) (int, map[string]any) {
b := e.browser(t)
if st, body := b.do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "correct horse battery"}); body["status"] != "totp_required" {
t.Fatalf("login = %d %v, want totp_required", st, body)
}
return b.do("POST", "/api/v1/auth/login/totp", map[string]any{"code": code})
}
if st, body := login(codes[0]); st != http.StatusOK {
t.Fatalf("login with recovery code = %d %v, want 200", st, body)
}
if st, _ := login(codes[0]); st != http.StatusUnauthorized {
t.Errorf("login with used recovery code = %d, want 401", st)
}
if st, _ := login(" " + upper(codes[1][:5]) + " " + codes[1][6:]); st != http.StatusOK {
t.Errorf("login with reformatted recovery code = %d, want 200", st)
}
if _, me := owner.do("GET", "/api/v1/me", nil); me["recovery_codes_left"] != float64(8) {
t.Errorf("recovery_codes_left = %v, want 8", me["recovery_codes_left"])
}
st, body := owner.do("POST", "/api/v1/me/totp/recovery-codes", map[string]any{"password": "correct horse battery", "code": codes[2]})
if st != http.StatusOK || len(body["recovery_codes"].([]any)) != 10 {
t.Fatalf("regenerate = %d %v, want 200 with 10 codes", st, body)
}
if st, _ := login(codes[3]); st != http.StatusUnauthorized {
t.Errorf("login with code from replaced set = %d, want 401", st)
}
if st, _ := login(body["recovery_codes"].([]any)[0].(string)); st != http.StatusOK {
t.Errorf("login with code from new set = %d, want 200", st)
}
st, _ = owner.do("POST", "/api/v1/me/totp/recovery-codes", map[string]any{"password": "wrong password!!", "code": codes[4]})
if st != http.StatusUnauthorized {
t.Errorf("regenerate with wrong password = %d, want 401", st)
}
}
func upper(s string) string {
b := []byte(s)
for i, c := range b {
if c >= 'a' && c <= 'z' {
b[i] = c - 32
}
}
return string(b)
}
+1
View File
@@ -83,6 +83,7 @@ func (s *Server) Mount(r gin.IRouter) {
me.POST("/totp/setup", s.totpSetup)
me.POST("/totp/enable", s.totpEnable)
me.POST("/totp/disable", s.totpDisable)
me.POST("/totp/recovery-codes", s.regenerateRecoveryCodes)
org := v1.Group("/org", auth.Require(), s.requireOwner())
org.GET("/sso", s.listSSOProviders)
+5
View File
@@ -57,6 +57,11 @@ func newEnv(t *testing.T) *env {
}
rdb := redis.NewClient(opts)
t.Cleanup(func() { _ = rdb.Close() })
// UPTIME_TEST_REDIS_URL must name a database reserved for tests; clearing
// it resets rate limits left over from earlier runs.
if err := rdb.FlushDB(ctx).Err(); err != nil {
t.Fatalf("FLUSHDB failed: %v", err)
}
key := make([]byte, 32)
_, _ = rand.Read(key)