otplib API Documentation / @otplib/hotp / verify
Function: verify()
verify(
options):Promise<VerifyResult>
Defined in: hotp/src/index.ts:264
Verify an HOTP code
Compares the provided token against the expected HOTP value using constant-time comparison to prevent timing attacks.
Parameters
options
HOTP verification options
Returns
Promise<VerifyResult>
Verification result with validity and optional delta
See
Counter Resynchronization (RFC 4226 Section 7.4)
When using a verification window, the delta value in the result indicates how many counter steps ahead the token was found. After successful verification, you should update the stored counter to prevent replay attacks:
ts
const nextCounter = counter + result.delta + 1;This ensures that the same token cannot be reused.
Examples
ts
import { verify } from '@otplib/hotp';
import { NodeCryptoPlugin } from '@otplib/plugin-crypto-node';
const result = await verify({
secret: new Uint8Array([1, 2, 3, 4, 5]),
counter: 0,
token: '123456',
crypto: new NodeCryptoPlugin(),
});
// Returns: { valid: true, delta: 0 }ts
// User's token was generated at counter 5, but server expects counter 3
const result = await verify({
secret,
counter: 3, // Server's stored counter
token: userToken,
counterTolerance: 5, // Allow up to 5 counters ahead
crypto: new NodeCryptoPlugin(),
});
if (result.valid) {
// Token matched at counter 3 + delta
// Update stored counter to prevent replay attacks
const nextCounter = 3 + result.delta + 1; // = 6
await saveCounter(userId, nextCounter);
}