one-time-pass
Version:
Zero dependencies Node/Deno/Bun/Browser TOTP and HOTP generator based on RFC 6238 and RFC 4226
62 lines (53 loc) • 2.54 kB
TypeScript
export declare function generateHOTP(secretKey: string, options?: HOTPOptions): Promise<string>;
export declare function generateSecret(length?: number): Promise<string>;
export declare function generateTOTP(secretKey: string, options?: Partial<TOTPOptions>): Promise<string>;
export declare type HmacAlgorithm = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';
export declare type HOTPOptions = {
algorithm?: HmacAlgorithm;
digits?: number;
counter?: number;
};
export declare type TOTPOptions = {
algorithm?: HmacAlgorithm;
period?: number;
digits?: number;
epoch?: number;
};
export declare type TOTPValidateOptions = TOTPOptions & {
window?: number;
};
/**
* Validates a TOTP token against a secret key, allowing for a window of tolerance.
*
* @param token The OTP token to validate.
* @param secretKey The Base32 encoded secret key.
* @param options Options for TOTP validation.
* - algorithm: HMAC algorithm (default "SHA-1")
* - period: time step in seconds (default 30)
* - digits: number of digits in token (default 6)
* - epoch: time in ms (default Date.now())
* - window: number of time steps before/after to allow (default 1)
*
* @returns
* - `0` if the token matches the current time period
* - `-1` if the token matches the previous time period (client clock is behind)
* - `1` if the token matches the next time period (client clock is ahead)
* - `null` if the token doesn't match any time period within the window
*
* @security
* - **window** parameter is critical for balancing security and usability:
* - `window = 0`: Maximum security (only current time step accepted). Recommended for high-security ops.
* - `window = 1`: Standard (accepts ±1 period). Good balance for most apps; tolerates up to ±period seconds drift.
* - `window ≥ 2`: Tolerant (for environments with poor time sync). Increases risk of replay attacks.
* - Always prefer the lowest window your use-case allows. For privileged or irreversible actions (transfers, password changes), set `window = 0`.
* - Ensure server and client clocks are synchronized (NTP recommended).
*
* @example
* // Standard validation
* validate(token, secret, {window: 1})
*
* // Strict validation, high security
* validate(token, secret, {window: 0})
*/
export declare function validate(token: string, secretKey: string, options?: Partial<TOTPValidateOptions>): Promise<number | null>;
export { }