# NOT MAINTAINED
---
**Jump to** — [Install](#install) · [Demo](#demo) · [Two-Factor Usage](#two-factor) · [General Usage](#general-usage) · [Documentation](#documentation) · [Contributing](#contributing) · [License](#license)
---
Speakeasy is a one-time passcode generator, ideal for use in two-factor
authentication, that supports Google Authenticator and other two-factor devices.
It is well-tested and includes robust support for custom token lengths,
authentication windows, hash algorithms like SHA256 and SHA512, and other
features, and includes helpers like a secret key generator.
Speakeasy implements one-time passcode generators as standardized by the
[Initiative for Open Authentication (OATH)][oath]. The HMAC-Based One-Time
Password (HOTP) algorithm defined by [RFC 4226][rfc4226] and the Time-Based
One-time Password (TOTP) algorithm defined in [RFC 6238][rfc6238] are
supported. This project incorporates code from [passcode][], originally a
fork of Speakeasy, and [notp][].
## Install
```sh
npm install --save speakeasy
```
## Demo
This demo uses the `generateSecret` method of Speakeasy to generate a secret key,
displays a Google Authenticator–compatible QR code which you can scan into your
phone's two-factor app, and shows the token, which you can verify with your
phone. Includes sample code. https://sedemo-mktb.rhcloud.com/
## Two-Factor Usage
Let's say you have a user that wants to enable two-factor authentication, and you intend to do two-factor authentication using an app like Google Authenticator, Duo Security, Authy, etc. This is a three-step process:
1. Generate a secret
2. Show a QR code for the user to scan in
3. Authenticate the token for the first time
### Generating a key
Use Speakeasy's key generator to get a key.
```js
var secret = speakeasy.generateSecret();
// Returns an object with secret.ascii, secret.hex, and secret.base32.
// Also returns secret.otpauth_url, which we'll use later.
```
This will generate a secret key of length 32, which will be the secret key for the user.
Now, we want to make sure that this secret works by validating the token that the user gets from it for the first time. In other words, we don't want to set this as the user's secret key just yet – we first want to verify their token for the first time. We need to persist the secret so that we can use it for token validation later.
So, store one of the encodings for the secret, preferably `secret.base32`, somewhere temporary, since we'll use that in the future to authenticate the user's first token.
```js
// Example for storing the secret key somewhere (varies by implementation):
user.two_factor_temp_secret = secret.base32;
```
### Displaying a QR code
Next, we'll want to display a QR code to the user so they can scan in the secret into their app. Google Authenticator and similar apps take in a QR code that holds a URL with the protocol `otpauth://`, which you get automatically from `secret.otpauth_url`.
Use a QR code module to generate a QR code that stores the data in `secret.otpauth_url`, and then display the QR code to the user. This is one simple way to do it, which generates a PNG data URL which you can put into an `` tag on a webpage:
```js
// Use the qrcode package
// npm install --save qrcode
var QRCode = require('qrcode');
// Get the data URL of the authenticator URL
QRCode.toDataURL(secret.otpauth_url, function(err, data_url) {
console.log(data_url);
// Display this data URL to the user in an tag
// Example:
write('');
});
```
Ask the user to scan this QR code into their authenticator app.
### Verifying the token
Finally, we want to make sure that the token on the server side and the token on the client side match. The best practice is to do a token check before fully enabling two-factor authenticaton for the user. This code applies to the first and subsequent token checks.
After the user scans the QR code, ask the user to enter in the token that they see in their app. Then, verify it against the secret.
```js
// Let's say the user says that the token they have is 132890
var userToken = '132890';
// Let's say we stored the user's temporary secret in a user object like above:
// (This is specific to your implementation)
var base32secret = user.two_factor_temp_secret;
```
```js
// Use verify() to check the token against the secret
var verified = speakeasy.totp.verify({ secret: base32secret,
encoding: 'base32',
token: userToken });
```
`verified` will be true if the token is successfully verified, false if not.
If successfully verified, you can now save the secret to the user's account and use the same process above whenever you need to use two-factor to authenticate the user, like during login.
```js
// Example for saving user's token (varies by implementation):
user.two_factor_secret = user.two_factor_temp_secret;
user.two_factor_enabled = true
```
Now you're done implementing two-factor authentication!
## General Usage
```js
var speakeasy = require("speakeasy");
```
#### Generating a key
```js
// Generate a secret key.
var secret = speakeasy.generateSecret({length: 20});
// Access using secret.ascii, secret.hex, or secret.base32.
```
#### Getting a time-based token for the current time
```js
// Generate a time-based token based on the base-32 key.
// HOTP (counter-based tokens) can also be used if `totp` is replaced by
// `hotp` (i.e. speakeasy.hotp()) and a `counter` is given in the options.
var token = speakeasy.totp({
secret: secret.base32,
encoding: 'base32'
});
// Returns token for the secret at the current time
// Compare this to user input
```
#### Verifying a token
```js
// Verify a given token
var tokenValidates = speakeasy.totp.verify({
secret: secret.base32,
encoding: 'base32',
token: '123456',
window: 6
});
// Returns true if the token matches
```
#### Verifying a token and calculating a delta
A TOTP is incremented every `step` time-step seconds. By default, the time-step
is 30 seconds. You may change the time-step using the `step` option, with units
in seconds.
```js
// Verify a given token is within 3 time-steps (+/- 2 minutes) from the server
// time-step.
var tokenDelta = speakeasy.totp.verifyDelta({
secret: secret.base32,
encoding: 'base32',
token: '123456',
window: 2,
step: 60
});
// Returns {delta: 0} where the delta is the time step difference
// between the given token and the current time
```
#### Getting a time-based token for a custom time
```js
var token = speakeasy.totp({
secret: secret.base32,
encoding: 'base32',
time: 1453667708 // specified in seconds
});
// Verify a time-based token for a custom time
var tokenValidates = speakeasy.totp.verify({
secret: secret.base32,
encoding: 'base32',
token: token,
time: 1453667708
});
```
#### Calculating a counter-based token
```js
// Get a counter-based token
var token = speakeasy.hotp({
secret: secret.base32,
encoding: 'base32',
counter: 123
});
// Verify a counter-based token
var tokenValidates = speakeasy.hotp.verify({
secret: secret.base32,
encoding: 'base32',
token: '123456',
counter: 123
});
```
#### Using other encodings
The default encoding (when `encoding` is not specified) is `ascii`.
```js
// Specifying an ASCII token for TOTP
// (encoding is 'ascii' by default)
var token = speakeasy.totp({
secret: secret.ascii
});
```
```js
// Specifying a hex token for TOTP
var token = speakeasy.totp({
secret: secret.hex,
encoding: 'hex'
});
```
#### Using other hash algorithms
The default hash algorithm is SHA1.
```js
// Specifying SHA256
var token = speakeasy.totp({
secret: secret.ascii,
algorithm: 'sha256'
});
```
```js
// Specifying SHA512
var token = speakeasy.totp({
secret: secret.ascii,
algorithm: 'sha512'
});
```
#### Getting an otpauth:// URL and QR code for non-SHA1 hash algorithms
```js
// Generate a secret, if needed
var secret = speakeasy.generateSecret();
// By default, generateSecret() returns an otpauth_url for SHA1
// Use otpauthURL() to get a custom authentication URL for SHA512
var url = speakeasy.otpauthURL({ secret: secret.ascii, label: 'Name of Secret', algorithm: 'sha512' });
// Pass URL into a QR code generator
```
#### Specifying a window for verifying HOTP and TOTP
Verify a HOTP token with counter value 42 and a window of 10. HOTP has a one-sided window, so this will check counter values from 42 to 52, inclusive, and return a `{ delta: n }` where `n` is the difference between the given counter value and the counter position at which the token was found, or `undefined` if it was not found within the window. See the
`hotp․verifyDelta(options)` documentation for more info.
```js
var token = speakeasy.hotp.verifyDelta({
secret: secret.ascii,
counter: 42,
token: '123456',
window: 10
});
```
How this works:
```
…
```
Verify a TOTP token at the current time with a window of 2. Since the default time step is 30 seconds, and TOTP has a two-sided window, this will check tokens between [current time minus two tokens before] and [current time plus two tokens after]. In other words, with a time step of 30 seconds, it will check the token at the current time, plus the tokens at the current time minus 30 seconds, minus 60 seconds, plus 30 seconds, and plus 60 seconds – basically, it will check tokens between a minute ago and a minute from now. It will return a `{ delta: n }` where `n` is the difference between the current time step and the counter position at which the token was found, or `undefined` if it was not found within the window. See the
`totp․verifyDelta(options)` documentation for more info.
```js
var verified = speakeasy.totp.verifyDelta({
secret: secret.ascii,
token: '123456',
window: 2
});
```
The mechanics of TOTP windows are the same as for HOTP, as shown above, just with two-sided windows, meaning that the `delta` value can be negative if the token is found before the given time or counter.
```
…
```
As shown previously, you can also change `verifyDelta()` to `verify()` to simply return a boolean if the given token is within the given window.
## Documentation
Full API documentation (in JSDoc format) is available below and at http://speakeasyjs.github.io/speakeasy/
### Functions
digest(options) ⇒
Buffer
Digest the one-time passcode options.
hotp(options) ⇒
String
Generate a counter-based one-time token.
hotp․verifyDelta(options) ⇒
Object
Verify a counter-based one-time token against the secret and return the delta.
hotp․verify(options) ⇒
Boolean
Verify a counter-based one-time token against the secret and return true if it
verifies.
totp(options) ⇒
String
Generate a time-based one-time token.
totp․verifyDelta(options) ⇒
Object
Verify a time-based one-time token against the secret and return the delta.
totp․verify(options) ⇒
Boolean
Verify a time-based one-time token against the secret and return true if it
verifies.
generateSecret(options) ⇒
Object |
GeneratedSecret
Generates a random secret with the set A-Z a-z 0-9 and symbols, of any length
(default 32).
gen