Skip to content

Instantly share code, notes, and snippets.

@manchicken
Last active September 6, 2024 15:36
Show Gist options
  • Save manchicken/17b49f5e0ce1f5fd7208be7c17ec27e3 to your computer and use it in GitHub Desktop.
Save manchicken/17b49f5e0ce1f5fd7208be7c17ec27e3 to your computer and use it in GitHub Desktop.
A demo of how to generate a TOTP
import process from 'node:process'
import { TOTP } from 'totp-generator'
// You'd put this into secrets manager.
// This is a dummy value taken from
// https://github.com/bellstrand/totp-generator?tab=readme-ov-file#custom-token-settings
// for convenience.
const totpSecret = 'JBSWY3DPEHPK3PXP'
// Easy-to-use error handling
const bailout = (msg) => {
console.error(msg)
process.exit(-1)
}
// Make the token, but if it returns something naughty let's crash.
const totpToken =
TOTP.generate(totpSecret)?.otp ??
bailout(
'Failed to get TOTP somehow?! The computer may be in the process of shutting down and/or detonation',
)
// If you're still here, you've got a helpful TOTP!
console.log(`The code is «${totpToken}»`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment