Skip to content

Commit cc797c1

Browse files
committed
fix: Fix GoogleTotpTest by adding timestamp parameter to verifyCode
- Add optional timestamp parameter to GoogleTotp::verifyCode() method - Update test to use specific timestamp (59s) instead of current time - Fixes time-sensitive TOTP verification test that was failing due to timing issues - Maintains backward compatibility with existing code - All 60 tests now passing with 207 assertions The test was failing because it calculated a code for a specific time slice (59s) but verifyCode() was using the current time, causing a mismatch. By adding timestamp injection capability, the test can now properly verify TOTP codes for specific time periods as intended by the RFC 6238 test case.
1 parent d15d273 commit cc797c1

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

src/Totp/GoogleTotp.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ public static function buildOtpAuthUrl(string $secret, string $label, string $is
1717
return sprintf('otpauth://totp/%s?secret=%s&issuer=%s&digits=%d&period=%d', $labelEnc, $secret, $issuerEnc, $digits, $period);
1818
}
1919

20-
public static function verifyCode(string $secret, string $code, int $digits = 6, int $period = 30, int $window = 1): bool
20+
public static function verifyCode(string $secret, string $code, int $digits = 6, int $period = 30, int $window = 1, ?int $timestamp = null): bool
2121
{
22-
$timeSlice = floor(time() / $period);
22+
$timeSlice = floor(($timestamp ?? time()) / $period);
2323
for ($i = -$window; $i <= $window; $i++) {
2424
$hash = self::hotp(self::base32Decode($secret), $timeSlice + $i);
2525
$otp = self::truncateToDigits($hash, $digits);

tests/GoogleTotpTest.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,13 @@
2929

3030
$period = 30;
3131
$digits = 6;
32-
$timeSlice = intdiv(59, $period); // from RFC 6238 example 59s
32+
$timestamp = 59; // from RFC 6238 example 59s
33+
$timeSlice = intdiv($timestamp, $period);
3334
$hash = $hotp->invoke(null, $base32Decode->invoke(null, $secret), $timeSlice);
3435
$expected = $truncate->invoke(null, $hash, $digits);
3536

36-
// Now verify using public API with window 0 to ensure exact slice
37-
$verified = GoogleTotp::verifyCode($secret, $expected, $digits, $period, 0);
37+
// Now verify using public API with the specific timestamp and window 0 to ensure exact slice
38+
$verified = GoogleTotp::verifyCode($secret, $expected, $digits, $period, 0, $timestamp);
3839
expect($verified)->toBeTrue();
3940
});
4041

0 commit comments

Comments
 (0)