// SPDX-License-Identifier: AGPL-3.0-or-later package auth import ( "bytes" "context" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/hex" "encoding/json" "errors" "image/png" "strings" "sync" "time" "github.com/pquerna/otp" "github.com/pquerna/otp/totp" "docwell/server/internal/store/pocketbase" ) // ---- Two-step sign-in with an authenticator app (TOTP) --------------------- // // PocketBase has no authenticator-app factor, so docwell-server adds one. // After any first factor (password, emailed code, OAuth) succeeds for an // account with TOTP on, the PocketBase token is held back under a short-lived // challenge and only handed out for a valid code, or a recovery code (each // works once). Clients never reach PocketBase directly, so there is no way // around the second step. // ErrInvalidCode is a wrong, expired or reused code. var ErrInvalidCode = errors.New("invalid code") // TOTPRequiredError means the first factor passed; the client must send a // code for Challenge to VerifyTOTP. type TOTPRequiredError struct{ Challenge string } func (e *TOTPRequiredError) Error() string { return "totp required" } const ( challengeTTL = 5 * time.Minute challengeAttempts = 5 recoveryCount = 10 ) type challenge struct { session Session expires time.Time attempts int } // totpState is the in-memory part of TOTP: pending challenges and the last // code each user signed in with (a code works once). type totpState struct { mu sync.Mutex challenges map[string]*challenge lastUsed map[string]string // user id → "secret-hash:code" } func newTOTPState() *totpState { return &totpState{challenges: map[string]*challenge{}, lastUsed: map[string]string{}} } type totpRecord struct { ID string `json:"id"` Email string `json:"email"` TOTPSecret string `json:"totp_secret"` TOTPPending string `json:"totp_pending"` TOTPEnabled bool `json:"totp_enabled"` RecoveryCodes json.RawMessage `json:"recovery_codes"` } func (s *Service) totpRecord(ctx context.Context, userID string) (totpRecord, error) { rec, err := pocketbase.Get[totpRecord](ctx, s.pb, "users", userID) return rec, tokenError(err) } func randomToken(n int) string { b := make([]byte, n) _, _ = rand.Read(b) return base64.RawURLEncoding.EncodeToString(b) } func hashCode(code string) string { sum := sha256.Sum256([]byte(strings.ToLower(strings.ReplaceAll(strings.TrimSpace(code), "-", "")))) return hex.EncodeToString(sum[:]) } // secondStep finishes a sign-in: with TOTP on, the session waits behind a // challenge. func (s *Service) secondStep(ctx context.Context, sess Session) (Session, error) { rec, err := s.totpRecord(ctx, sess.User.ID) if err != nil { return Session{}, err } sess.User.TOTP = rec.TOTPEnabled if !rec.TOTPEnabled { return sess, nil } id := randomToken(24) now := s.now() s.totp.mu.Lock() defer s.totp.mu.Unlock() for k, c := range s.totp.challenges { if now.After(c.expires) { delete(s.totp.challenges, k) } } s.totp.challenges[id] = &challenge{session: sess, expires: now.Add(challengeTTL)} return Session{}, &TOTPRequiredError{Challenge: id} } // VerifyTOTP completes a sign-in held back by secondStep with an // authenticator code or a recovery code. func (s *Service) VerifyTOTP(ctx context.Context, challengeID, code string) (Session, error) { s.totp.mu.Lock() ch, ok := s.totp.challenges[challengeID] if ok && (s.now().After(ch.expires) || ch.attempts >= challengeAttempts) { delete(s.totp.challenges, challengeID) ok = false } if ok { ch.attempts++ } s.totp.mu.Unlock() if !ok { return Session{}, ErrInvalidToken } rec, err := s.totpRecord(ctx, ch.session.User.ID) if err != nil { return Session{}, err } if !s.checkCode(ctx, rec, code, true) { return Session{}, ErrInvalidCode } s.totp.mu.Lock() delete(s.totp.challenges, challengeID) s.totp.mu.Unlock() return ch.session, nil } // checkCode accepts a current authenticator code (once) or, with recovery, // an unused recovery code, which it uses up. func (s *Service) checkCode(ctx context.Context, rec totpRecord, code string, recovery bool) bool { code = strings.TrimSpace(code) if rec.TOTPSecret == "" || code == "" { return false } if len(code) == 6 && strings.Trim(code, "0123456789") == "" { ok, _ := totp.ValidateCustom(code, rec.TOTPSecret, s.now(), totp.ValidateOpts{ Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }) if !ok { return false } used := hashCode(rec.TOTPSecret) + ":" + code s.totp.mu.Lock() defer s.totp.mu.Unlock() if s.totp.lastUsed[rec.ID] == used { return false } s.totp.lastUsed[rec.ID] = used return true } if !recovery { return false } var hashes []string _ = json.Unmarshal(rec.RecoveryCodes, &hashes) want := hashCode(code) for i, h := range hashes { if subtle.ConstantTimeCompare([]byte(h), []byte(want)) == 1 { rest := append(append([]string{}, hashes[:i]...), hashes[i+1:]...) _, err := pocketbase.Update[totpRecord](ctx, s.pb, "users", rec.ID, map[string]any{"recovery_codes": rest}) return err == nil } } return false } // TOTPStatus is whether an account uses an authenticator app. type TOTPStatus struct { Enabled bool `json:"enabled"` // RecoveryCodesLeft is how many unused recovery codes remain. RecoveryCodesLeft int `json:"recoveryCodesLeft"` } func (s *Service) TOTPStatus(ctx context.Context, userID string) (TOTPStatus, error) { rec, err := s.totpRecord(ctx, userID) if err != nil { return TOTPStatus{}, err } var hashes []string _ = json.Unmarshal(rec.RecoveryCodes, &hashes) return TOTPStatus{Enabled: rec.TOTPEnabled, RecoveryCodesLeft: len(hashes)}, nil } // TOTPSetup is a new secret to add to an authenticator app. type TOTPSetup struct { Secret string `json:"secret"` // URL is the otpauth:// address the QR code holds. URL string `json:"url"` // QR is a PNG data: URL of the QR code. QR string `json:"qr"` } // StartTOTP creates a pending secret for u (shown once; confirmed by EnableTOTP). func (s *Service) StartTOTP(ctx context.Context, u User, issuer string) (TOTPSetup, error) { rec, err := s.totpRecord(ctx, u.ID) if err != nil { return TOTPSetup{}, err } if rec.TOTPEnabled { return TOTPSetup{}, &ValidationError{Fields: map[string]string{"code": "Two-step sign-in is already on."}} } if issuer == "" { issuer = "Docwell" } key, err := totp.Generate(totp.GenerateOpts{Issuer: issuer, AccountName: u.Email}) if err != nil { return TOTPSetup{}, err } if _, err := pocketbase.Update[totpRecord](ctx, s.pb, "users", u.ID, map[string]any{"totp_pending": key.Secret()}); err != nil { return TOTPSetup{}, err } out := TOTPSetup{Secret: key.Secret(), URL: key.URL()} if img, err := key.Image(240, 240); err == nil { var buf bytes.Buffer if png.Encode(&buf, img) == nil { out.QR = "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()) } } return out, nil } // EnableTOTP turns two-step sign-in on once code matches the pending secret, // and returns the recovery codes (shown only now). func (s *Service) EnableTOTP(ctx context.Context, u User, code string) ([]string, error) { rec, err := s.totpRecord(ctx, u.ID) if err != nil { return nil, err } if rec.TOTPPending == "" { return nil, &ValidationError{Fields: map[string]string{"code": "Start the setup first."}} } pending := rec pending.TOTPSecret = rec.TOTPPending if !s.checkCode(ctx, pending, code, false) { return nil, ErrInvalidCode } codes := make([]string, recoveryCount) hashes := make([]string, recoveryCount) for i := range codes { raw := strings.ToLower(base64.RawStdEncoding.EncodeToString([]byte(randomToken(6)))) raw = strings.Map(func(r rune) rune { if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' { return r } return -1 }, raw) for len(raw) < 10 { raw += "x" } codes[i] = raw[:5] + "-" + raw[5:10] hashes[i] = hashCode(codes[i]) } if _, err := pocketbase.Update[totpRecord](ctx, s.pb, "users", u.ID, map[string]any{ "totp_secret": rec.TOTPPending, "totp_pending": "", "totp_enabled": true, "recovery_codes": hashes, }); err != nil { return nil, err } s.Forget(u.ID) return codes, nil } // DisableTOTP turns two-step sign-in off; it takes a current code or a // recovery code, so a stolen session alone cannot. func (s *Service) DisableTOTP(ctx context.Context, u User, code string) error { rec, err := s.totpRecord(ctx, u.ID) if err != nil { return err } if !rec.TOTPEnabled { return nil } if !s.checkCode(ctx, rec, code, true) { return ErrInvalidCode } return s.ResetTOTP(ctx, u.ID) } // ResetTOTP turns two-step sign-in off without a code (an admin helping // someone who lost their phone; the caller checks the rights). func (s *Service) ResetTOTP(ctx context.Context, userID string) error { _, err := pocketbase.Update[totpRecord](ctx, s.pb, "users", userID, map[string]any{ "totp_secret": "", "totp_pending": "", "totp_enabled": false, "recovery_codes": []string{}, }) s.Forget(userID) return tokenError(err) }