npm.io
1.1.0 • Published 6 months agoCLI

totp-auth

Licence
ISC
Version
1.1.0
Deps
1
Size
8 kB
Vulns
0
Weekly
0
Stars
2

TOTP Auth

npm-badge ts-badge prettier-badge license-badge

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

source code

Installation

# pnpm
pnpm i totp-auth

# npm
npm i totp-auth

Usage

CLI
totp-auth JBSWY3DPEHPK3PXP
# {"passcode":"123456","expire-seconds":17}

The CLI accepts the TOTP secret as the first positional argument and writes only JSON to stdout on success. The expire-seconds value is the number of seconds remaining before the current passcode rotates.

Invalid or missing secrets return a JSON error on stderr and exit with a non-zero status.

totp-auth asdf
# {"error":"invalid secret"}
Library
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" 

Technical Details

npm package download

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

Questions?

Open a github issue or ping me on Twitter twitter-icon

Keywords