sdk-client-asafe-v.1.0
v1.0.0
Published
TOTP (RFC 6238) / Google Authenticator compatible 2FA helper.
Maintainers
Readme
sdk-client-asafe-v.1.0
Small TOTP (RFC 6238) helper compatible with Google Authenticator / Authy.
Install
npm i sdk-client-asafe-v.1.0Usage
Basic Example
import { Asafe2FA } from "sdk-client-asafe-v.1.0";
const a2fa = new Asafe2FA();
// Generate a secret key (base32 encoded)
const secret = a2fa.generateSecret();
// Create an OTP Auth URL for QR code scanning
const url = a2fa.getOtpAuthUrl("[email protected]", "MyCompany", secret);
// Get the current OTP code
const otp = a2fa.getCurrentOtp(secret);
// Verify the OTP code
const ok = a2fa.verifyKey(secret, otp, 1);Understanding the window Parameter
The window parameter in verifyKey() allows for time drift tolerance. Since TOTP codes change every 30 seconds (by default), small clock differences between the server and the user's device can cause verification to fail.
How it works:
window = 0: Only accepts the current time period's codewindow = 1(default): Accepts codes from the current period, the previous period, and the next period (±30 seconds)window = 2: Accepts codes from ±2 periods (±60 seconds)
Example:
// Strict verification - only current code
const strict = a2fa.verifyKey(secret, userInput, 0);
// Default - allows ±30 seconds tolerance (recommended)
const normal = a2fa.verifyKey(secret, userInput, 1);
// More lenient - allows ±60 seconds tolerance
const lenient = a2fa.verifyKey(secret, userInput, 2);When to use different values:
- Use
window = 0for maximum security (but may fail with clock drift) - Use
window = 1for most applications (good balance of security and usability) - Use
window = 2or higher if you expect significant clock synchronization issues
API
generateSecret(length?: number): string
Generates a random base32-encoded secret key.
length: Optional. Number of characters (default: 32, ~160 bits)
getOtpAuthUrl(account: string, issuer: string, secret: string): string
Creates an otpauth:// URL compatible with Google Authenticator, Authy, and other TOTP apps.
account: User identifier (e.g., email address)issuer: Service name (e.g., "MyCompany")secret: The secret key generated bygenerateSecret()
getCurrentOtp(secret: string, options?: TotpOptions): string
Generates the current TOTP code for the given secret.
secret: The secret keyoptions: Optional TOTP configuration (period, digits, algorithm)
verifyKey(secret: string, token: string, window?: number, options?: TotpOptions): boolean
Verifies if a TOTP token is valid.
secret: The secret keytoken: The OTP code to verify (user input)window: Optional. Time drift tolerance in periods (default: 1). See Understanding thewindowParameter aboveoptions: Optional TOTP configuration- Returns:
trueif the token is valid,falseotherwise
License
MIT
