package domain import ( "crypto/rand" "errors" "fmt" "io" "log/slog" "math/big" "regexp" "time" ) const ( // VerificationCodeDigits is the length of the code in a verification // message. The contract pattern is ^[0-9]{6}$. VerificationCodeDigits = 6 // VerificationCodeMaxFailedAttempts is the number of failed attempts // against one open code after which the code and its token are burned. // The storage check constraint repeats this value. VerificationCodeMaxFailedAttempts = 5 // VerificationCodeLifetime bounds how long a code works. A token lasts // longer, so the code ends first; the code expiry is the earlier of the // two, see NewEmailToken. VerificationCodeLifetime = 30 * time.Minute // verificationCodeSpace is the number of distinct codes: 000000 to 999999. verificationCodeSpace = 1_000_000 ) var ( // ErrInvalidVerificationCode reports a code that is not six ASCII digits. // Its message never contains the rejected value. ErrInvalidVerificationCode = errors.New("invalid verification code") verificationCodeSpaceBig = big.NewInt(verificationCodeSpace) verificationCodePattern = regexp.MustCompile(`^[0-9]{6}$`) ) // VerificationCode is the six-digit code of a verification message. Only the // holder sees the value; String, GoString, Format, and LogValue redact it so // that it does not reach logs by accident. Reveal returns it for the one place // that must send it. The value sits behind a pointer, as in SecretToken. type VerificationCode struct { value *string } // NewVerificationCode returns a code drawn uniformly from 000000 to 999999 // with crypto/rand. func NewVerificationCode() (VerificationCode, error) { return newVerificationCode(rand.Reader) } // newVerificationCode draws from random. crypto/rand.Int rejects the draws // above the bound instead of reducing them modulo it, so every code is equally // likely. func newVerificationCode(random io.Reader) (VerificationCode, error) { number, err := rand.Int(random, verificationCodeSpaceBig) if err != nil { return VerificationCode{}, fmt.Errorf("domain.NewVerificationCode - draw code: %w", err) } return VerificationCode{value: newRedactedValue(fmt.Sprintf("%0*d", VerificationCodeDigits, number.Int64()))}, nil } // ParseVerificationCode accepts exactly six ASCII digits from a request. Spaces // and separators are rejected rather than stripped, so the contract stays exact. func ParseVerificationCode(raw string) (VerificationCode, error) { if !verificationCodePattern.MatchString(raw) { return VerificationCode{}, fmt.Errorf("domain.ParseVerificationCode - code must have %d digits: %w", VerificationCodeDigits, ErrInvalidVerificationCode) } return VerificationCode{value: newRedactedValue(raw)}, nil } // Reveal returns the digits for delivery to the holder, or for the keyed // digest. Never store or log the result. func (code VerificationCode) Reveal() string { return redactedValue(code.value) } // IsZero reports a VerificationCode not built by NewVerificationCode or // ParseVerificationCode. func (code VerificationCode) IsZero() bool { return code.value == nil } func (code VerificationCode) String() string { return redactedSecret } func (code VerificationCode) GoString() string { return redactedSecret } // Format redacts every verb; without it %d would print the digits. func (code VerificationCode) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } func (code VerificationCode) LogValue() slog.Value { return slog.StringValue(redactedSecret) } // VerificationCodeHash is the keyed digest of a VerificationCode that storage // keeps. It is an HMAC under a server secret: the code space has only a // million values, so an unkeyed digest could be reversed by enumeration. type VerificationCodeHash [SecretTokenHashSize]byte // IsZero reports the all-zero value, which marks a missing digest. func (hash VerificationCodeHash) IsZero() bool { return hash == VerificationCodeHash{} } // EmailCode is the code state of an email token: its keyed digest and the end // of its validity. type EmailCode struct { Hash VerificationCodeHash ExpiresAt time.Time }