1.0.11 • Published 1 year ago

totp-auth v1.0.11

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

TOTP Auth

Easy-to-use timebased one time password(TOTP) generator, compatible with Google Authenticator.

npm NPM

Installation

# pnpm
pnpm i totp-auth

# npm
npm i totp-auth

Usage

import { createTOTP, countdown } from "totp-auth"
import { setInterval } from "timers/promises"

//secret from service provider
const secret = "abcd1234"

let totp = createTOTP(secret)
let expire = countdown()

// current TOTP and expiring time in seconds
console.log(`TOTP: ${totp}, expire: ${expire}`)

// keep counting down and refresh TOTP every 30 sec
for await (let _ of setInterval(1000)) {
  const cnt = countdown()
  if (cnt >= expire) totp = createTOTP(secret)
  expire = cnt
  console.log(`TOTP: ${totp}, expire: ${expire}`)
}

Error Handling

Not all strings can be secret key, invalid secret key will return a customizable error message.

// invalid secret -> default error message
createTOTP('asdf') // returns "invalid secret" 

// invalid secret w/ custom error message
createTOTP('asdf', undefined, 'bad key') // returns "bad key" 

Source Code

https://github.com/hoishing/totp-auth

code logic

  1. create base32 representation of the credential
  2. calculate HMAC hash from the credential with current time
  3. shift and trim 6 digit TOTP from the hash above

Tests

Both createTOTP and countdown are pure functions. Unit test with Jest are included.

The TOTP output could also simply verified by Google Authenticator output.

Credits

Algorithm ref: http://jsfiddle.net/russau/ch8PK/ HMAC lib: https://github.com/Caligatio/jsSHA

FAQ

Need Help?

Open a github issue or ping me on Twitter

1.0.11

1 year ago

1.0.10

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago