Files
3x-ui/internal/util/totp/totp_test.go
T
sdhfsl d440c2b932 fix(panel): accept 2FA codes from adjacent TOTP windows (#6546)
* fix(panel): accept 2FA codes from adjacent TOTP windows

CheckUser compared only gotp.Now(), so a code submitted at the end of
its 30s window (or with slight client/server clock drift) failed with
'invalid 2fa code', while the immediate retry in the next window
succeeded. Accept current +/-1 window, the standard TOTP skew
tolerance.

Fixes MHSanaei/3x-ui#6535

* fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode

Move the +/-1 window helper to internal/util/totp so both 2FA
acceptance points use it: login (CheckUser) and disable/rebind plus
username/password changes (VerifyTwoFactorCode). Also shrink comments
to the 2-line house rule and anchor the unit test mid-window to avoid
a step-boundary flake.

Addresses review on #6546 (MEDIUM + 2 LOWs).

---------

Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
2026-09-15 15:42:30 +03:00

35 lines
1.0 KiB
Go

package totp
import (
"testing"
"time"
"github.com/xlzd/gotp"
)
func TestVerifyWithSkew(t *testing.T) {
secret := "JBSWY3DPEHPK3PXP"
totp := gotp.NewDefaultTOTP(secret)
// Anchor mid-window so a step boundary can't fall between sampling and verify.
now := time.Unix((time.Now().Unix()/30)*30+15, 0).UTC()
if !VerifyWithSkew(secret, totp.AtTime(now), now) {
t.Fatal("current window code should verify")
}
if !VerifyWithSkew(secret, totp.AtTime(now.Add(-30*time.Second)), now) {
t.Fatal("previous window code should verify (clock skew)")
}
if !VerifyWithSkew(secret, totp.AtTime(now.Add(30*time.Second)), now) {
t.Fatal("next window code should verify (clock skew)")
}
if VerifyWithSkew(secret, totp.AtTime(now.Add(-60*time.Second)), now) {
t.Fatal("code two windows old should not verify")
}
if VerifyWithSkew(secret, totp.AtTime(now.Add(60*time.Second)), now) {
t.Fatal("code two windows ahead should not verify")
}
if VerifyWithSkew(secret, "000000", now) {
t.Fatal("wrong code should not verify")
}
}