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
This commit is contained in:
sdhfsl
2026-09-15 18:28:52 +08:00
parent d52b598abf
commit 959e6fd62b
2 changed files with 55 additions and 1 deletions
@@ -0,0 +1,33 @@
package panel
import (
"testing"
"time"
"github.com/xlzd/gotp"
)
func TestVerifyTOTPWithSkew(t *testing.T) {
secret := "JBSWY3DPEHPK3PXP"
totp := gotp.NewDefaultTOTP(secret)
now := time.Now()
if !verifyTOTPWithSkew(secret, totp.AtTime(now)) {
t.Fatal("current window code should verify")
}
if !verifyTOTPWithSkew(secret, totp.AtTime(now.Add(-30*time.Second))) {
t.Fatal("previous window code should verify (clock skew)")
}
if !verifyTOTPWithSkew(secret, totp.AtTime(now.Add(30*time.Second))) {
t.Fatal("next window code should verify (clock skew)")
}
if verifyTOTPWithSkew(secret, totp.AtTime(now.Add(-60*time.Second))) {
t.Fatal("code two windows old should not verify")
}
if verifyTOTPWithSkew(secret, totp.AtTime(now.Add(60*time.Second))) {
t.Fatal("code two windows ahead should not verify")
}
if verifyTOTPWithSkew(secret, "000000") {
t.Fatal("wrong code should not verify")
}
}