package auth import ( "context" "time" "github.com/google/uuid" "github.com/pquerna/otp" "github.com/pquerna/otp/totp" "github.com/redis/go-redis/v9" ) const totpIssuer = "uptimesebi" // NewTOTPKey generates a secret for account using the defaults every common // authenticator app supports (SHA-1, 6 digits, 30 s). func NewTOTPKey(account string) (*otp.Key, error) { return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account}) } // TOTPVerifier rejects a code that was already accepted once, so an observed // code cannot be replayed within its validity window. type TOTPVerifier struct { rdb redis.UniversalClient now func() time.Time } // NewTOTPVerifier returns a verifier that records used codes in rdb. func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier { return &TOTPVerifier{rdb: rdb, now: time.Now} } // Verify accepts code for secret within one step of clock skew, at most once // per user. func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) { ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{ Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }) if err != nil || !ok { return false, nil } fresh, err := v.rdb.SetNX(ctx, "totp_used:"+user.String()+":"+code, 1, 2*time.Minute).Result() if err != nil { return false, err } return fresh, nil }