UNPKG

otp-io

Version:

🕖 Typed library to work 2fa via Google Authenticator/Time-based TOTP/Hmac-based HOTP

41 lines • 1.58 kB
import {getDefaultHOTPOptions}from'./hotp.options.mjs';import {getDefaultTOTPOptions}from'./totp.options.mjs';import {exportKey}from'./key.actions.mjs';/** * * * @export * @param {UriOptions} options * @return {string} {string} */ function getKeyUri(options) { const title = options.issuer ? `${encodeURIComponent(options.issuer)}:${encodeURIComponent(options.name)}` : encodeURIComponent(options.name); const url = new URL(`otpauth://${options.type}/${title}`); url.searchParams.set("secret", exportKey(options.secret)); if (options.issuer) { url.searchParams.set("issuer", options.issuer); } let algorithm; let digits; switch (options.type) { case "hotp": { const merged = Object.assign(Object.assign({}, getDefaultHOTPOptions()), options); algorithm = merged.algorithm; digits = merged.digits; url.searchParams.set("counter", merged.counter.toString()); break; } case "totp": { const merged = Object.assign(Object.assign({}, getDefaultTOTPOptions()), options); algorithm = merged.algorithm; digits = merged.digits; url.searchParams.set("period", merged.stepSeconds.toString()); break; } default: { throw new Error(`Invalid method type: "${options.type}"`); } } url.searchParams.set("algorithm", algorithm.toUpperCase()); url.searchParams.set("digits", digits.toString()); return url.toString(); }export{getKeyUri};