34 lines
982 B
TypeScript
34 lines
982 B
TypeScript
import { authenticator } from "otplib";
|
|
|
|
// Laravel Fortify uses pragmarx/google2fa: HMAC-SHA1, 6 digits, 30s period.
|
|
// otplib already defaults to SHA1/6/30; window=1 tolerates one step of skew.
|
|
authenticator.options = { window: 1 };
|
|
|
|
/** Verify a 6-digit TOTP code against a base32 secret. */
|
|
export function verifyTotp(token: string, secret: string): boolean {
|
|
try {
|
|
return authenticator.check(token, secret);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** Current TOTP code for a secret (used in tests / tooling). */
|
|
export function generateTotp(secret: string): string {
|
|
return authenticator.generate(secret);
|
|
}
|
|
|
|
/** Generate a fresh base32 secret for enrolling a new authenticator. */
|
|
export function generateTotpSecret(): string {
|
|
return authenticator.generateSecret();
|
|
}
|
|
|
|
/** otpauth:// URI for provisioning a QR code. */
|
|
export function totpKeyUri(
|
|
secret: string,
|
|
accountName: string,
|
|
issuer: string,
|
|
): string {
|
|
return authenticator.keyuri(accountName, issuer, secret);
|
|
}
|