Files
davidandClaude Opus 5.5 8040512a18 Phase 10, part 3: signing in and out, resets, locks and two-factor
The server edition now starts. Sign-in by email and password, limited per
address and per IP; ten failures in a row lock the account and email its
owner, and a reset by email (or an admin) unlocks it. Settings → Your
account has the profile, the password, where you're signed in, and
two-factor sign-in with an authenticator app (TOTP, from a QR code) and
ten recovery codes. The app's own mail goes through SUPERMARKET_MAIL_URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:01:29 -07:00

176 lines
5.2 KiB
Go

package users
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/subtle"
"encoding/base32"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"supermarket/internal/db"
)
// Two-factor sign-in with an authenticator app: TOTP (RFC 6238), six
// digits every 30 seconds, as every app does by default. The secret is
// kept in the secrets store (encrypted on the server editions), under
// TOTPSecretName.
// TOTPSecretName is where a user's authenticator secret is kept; while it's
// being set up, TOTPPendingName.
func TOTPSecretName(user int64) string { return fmt.Sprintf("totp:%d", user) }
func TOTPPendingName(user int64) string { return fmt.Sprintf("totp-pending:%d", user) }
const totpPeriod = 30
var b32 = base32.StdEncoding.WithPadding(base32.NoPadding)
// NewTOTPSecret is a new authenticator secret, in base32 as apps take it.
func NewTOTPSecret() (string, error) {
b := make([]byte, 20)
if _, err := rand.Read(b); err != nil {
return "", err
}
return b32.EncodeToString(b), nil
}
// TOTPURL is the otpauth:// address an app reads from the QR code.
func TOTPURL(issuer, account, secret string) string {
v := url.Values{"secret": {secret}, "issuer": {issuer}, "algorithm": {"SHA1"}, "digits": {"6"}, "period": {"30"}}
return "otpauth://totp/" + url.PathEscape(issuer+":"+account) + "?" + v.Encode()
}
// totpAt is the code for a time step.
func totpAt(key []byte, step int64) string {
var msg [8]byte
binary.BigEndian.PutUint64(msg[:], uint64(step))
mac := hmac.New(sha1.New, key)
mac.Write(msg[:])
sum := mac.Sum(nil)
off := sum[len(sum)-1] & 0x0f
n := binary.BigEndian.Uint32(sum[off:off+4]) & 0x7fffffff
return fmt.Sprintf("%06d", n%1000000)
}
// TOTPCode is the code for a time: for tests.
func TOTPCode(secret string, t time.Time) string {
key, _ := b32.DecodeString(strings.ToUpper(secret))
return totpAt(key, t.Unix()/totpPeriod)
}
// CheckTOTP checks a code against the secret, allowing a step either side
// for clocks that differ. A code works only after the step last used
// (after), so one seen over someone's shoulder can't be used again. It
// returns the code's step.
func CheckTOTP(secret, code string, after int64, now time.Time) (int64, bool) {
code = strings.Join(strings.Fields(code), "")
if len(code) != 6 {
return 0, false
}
key, err := b32.DecodeString(strings.ToUpper(secret))
if err != nil || len(key) == 0 {
return 0, false
}
cur := now.Unix() / totpPeriod
for _, step := range []int64{cur - 1, cur, cur + 1} {
if step > after && subtle.ConstantTimeCompare([]byte(totpAt(key, step)), []byte(code)) == 1 {
return step, true
}
}
return 0, false
}
// UseTOTPStep records the step of a code that was used.
func UseTOTPStep(d *db.DB, u *User, step int64) error {
_, err := d.Exec(`UPDATE users SET totp_step = ? WHERE id = ? AND totp_step < ?`, step, u.ID, step)
if err == nil {
u.totpStep = step
}
return err
}
// TOTPStep is the step of the last code used.
func (u *User) TOTPStep() int64 { return u.totpStep }
// NewRecoveryCodes makes ten single-use codes, like 7kq2-m9xw-4tpd, and
// returns them with the hashes to keep.
func NewRecoveryCodes() (codes, hashes []string, err error) {
const alphabet = "abcdefghjkmnpqrstuvwxyz23456789" // no 0/o, 1/l/i
for i := 0; i < 10; i++ {
b := make([]byte, 12)
if _, err := rand.Read(b); err != nil {
return nil, nil, err
}
var sb strings.Builder
for j, c := range b {
if j > 0 && j%4 == 0 {
sb.WriteByte('-')
}
sb.WriteByte(alphabet[int(c)%len(alphabet)])
}
codes = append(codes, sb.String())
hashes = append(hashes, hashCode(sb.String()))
}
return codes, hashes, nil
}
func hashCode(code string) string {
code = strings.ToLower(strings.NewReplacer("-", "", " ", "").Replace(strings.TrimSpace(code)))
sum := sha256.Sum256([]byte(code))
return hex.EncodeToString(sum[:])
}
// SetTwoFactor turns two-factor sign-in on, with new recovery codes'
// hashes, or off (hashes nil). The secret is the caller's to keep or drop.
func SetTwoFactor(d *db.DB, u *User, on bool, hashes []string) error {
if hashes == nil {
hashes = []string{}
}
js, _ := json.Marshal(hashes)
flag := 0
if on {
flag = 1
}
if _, err := d.Exec(`UPDATE users SET two_factor = ?, recovery_codes = ?, totp_step = 0 WHERE id = ?`, flag, string(js), u.ID); err != nil {
return err
}
u.TwoFactor, u.recoveryCodes, u.RecoveryLeft, u.totpStep = on, hashes, len(hashes), 0
return nil
}
// UseRecoveryCode uses up one of the user's recovery codes, if code is one.
func UseRecoveryCode(d *db.DB, u *User, code string) (bool, error) {
h := hashCode(code)
left := make([]string, 0, len(u.recoveryCodes))
found := false
for _, c := range u.recoveryCodes {
if !found && subtle.ConstantTimeCompare([]byte(c), []byte(h)) == 1 {
found = true
continue
}
left = append(left, c)
}
if !found {
return false, nil
}
js, _ := json.Marshal(left)
old, _ := json.Marshal(u.recoveryCodes)
// Only if no one else used a code meanwhile: each works once.
res, err := d.Exec(`UPDATE users SET recovery_codes = ? WHERE id = ? AND recovery_codes = ?`, string(js), u.ID, string(old))
if err != nil {
return false, err
}
if n, _ := res.RowsAffected(); n != 1 {
return false, nil
}
u.recoveryCodes, u.RecoveryLeft = left, len(left)
return true, nil
}