### Install speakeasy via npm Source: https://github.com/speakeasyjs/speakeasy/wiki/Home Install the speakeasy package using npm. This is the first step before using any of the two-factor authentication functions. ```sh npm install --save speakeasy ``` -------------------------------- ### hotp.verify usage example Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/hotp.md Example of using speakeasy.hotp.verify to check a token with a window of 10. The output is true for the given secret, token, and counter. ```javascript var speakeasy = require('speakeasy'); var ok = speakeasy.hotp.verify({ secret: '12345678901234567890', token: '969429', counter: 0, window: 10 }); console.log(ok); // true ``` -------------------------------- ### Example usage of generateSecret() Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/types.md Shows how to generate a secret and access its properties. The returned object includes ascii, hex, base32, and otpauth_url fields. ```javascript var speakeasy = require('speakeasy'); var secret = speakeasy.generateSecret(); // secret: { ascii: String, hex: String, base32: String, otpauth_url: String } console.log(secret.ascii, secret.hex, secret.base32, secret.otpauth_url); ``` -------------------------------- ### Set up user token and temporary secret Source: https://github.com/speakeasyjs/speakeasy/wiki/Verify-The-Token Before verifying, capture the token the user enters from their authenticator app and retrieve the temporary secret stored during the QR code setup. The secret is stored in a user object specific to your implementation. ```javascript // 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; ``` -------------------------------- ### Store the secret base32 temporarily Source: https://github.com/speakeasyjs/speakeasy/wiki/Home Example of persisting the secret.base32 value for later token validation. The actual storage method varies by implementation. ```javascript // Example for storing the secret key somewhere (varies by implementation): user.two_factor_temp_secret = secret.base32; ``` -------------------------------- ### Generate QR code data URL from otpauth_url using node-qrcode Source: https://github.com/speakeasyjs/speakeasy/wiki/Display-QR-Code Use the node-qrcode package to generate a PNG data URL from the secret's otpauth_url, which can be displayed in an tag. Requires installing node-qrcode with 'npm install --save node-qrcode'. ```javascript // Use the node-qrcode package // npm install --save node-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(''); }); ``` -------------------------------- ### Save user's secret after successful verification Source: https://github.com/speakeasyjs/speakeasy/wiki/Verify-The-Token After verification succeeds, store the secret permanently on the user's account and enable two-factor authentication. This example is implementation-specific. ```javascript // Example for saving user's token (varies by implementation): user.two_factor_secret = user.two_factor_temp_secret; user.two_factor_enabled = true ``` -------------------------------- ### Generate a secret key with speakeasy.generateSecret() Source: https://github.com/speakeasyjs/speakeasy/wiki/Home Generates a secret key of length 32. Returns an object with ascii, hex, base32, and otpauth_url properties. The otpauth_url is used later for QR code display. ```javascript 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. ``` -------------------------------- ### generateSecretASCII example usage Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/generateSecret.md Example of calling generateSecretASCII with length 16 and symbols true, producing a key that includes symbols. The output is logged to the console. ```javascript var speakeasy = require('speakeasy'); var key = speakeasy.generateSecretASCII(16, true); console.log(key); // e.g. 'yQ0b!eT9vX2nA1uW$' (contains symbols) ``` -------------------------------- ### Get an otpauth:// URL and QR code for non-SHA1 hash algorithms Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Generate a secret and obtain a custom otpauth URL for SHA512 using otpauthURL(). The URL can be passed to a QR code generator. ```javascript // 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 ``` -------------------------------- ### Get and verify a time-based token for a custom time Source: https://github.com/speakeasyjs/speakeasy/wiki/General-Usage-for-Time-Based-Token Generate and verify a TOTP token for a specific time specified in seconds. ```javascript 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 }); ``` -------------------------------- ### otpauthURL(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Generates a Google Authenticator-compatible otpauth:// URL for passing a secret to a mobile device. This URL can be used to generate a QR code for easy setup. ```APIDOC ## otpauthURL(options) ### Description Generate a Google Authenticator-compatible otpauth:// URL for passing the secret to a mobile device to install the secret. Authenticator considers TOTP codes valid for 30 seconds and presents 6 digit codes to the user. To generate a suitable QR Code, pass the generated URL to a QR Code generator, such as the `qr-image` module. ### Method Function ### Endpoint otpauthURL(options) ### Parameters #### Options Object - **options** (Object) - Required - The options object. - **options.secret** (String) - Required - Shared secret key. - **options.label** (String) - Required - Used to identify the account with which the secret key is associated, e.g. the user's email address. - **options.type** (String) - Optional - Either "hotp" or "totp". Default: "totp". - **options.counter** (Integer) - Optional - The initial counter value, required for HOTP. - **options.issuer** (String) - Optional - The provider or service with which the secret key is associated. - **options.algorithm** (String) - Optional - Hash algorithm (sha1, sha256, sha512). Default: "sha1". - **options.digits** (Integer) - Optional - The number of digits for the one-time passcode. Currently ignored by Google Authenticator. Default: 6. - **options.period** (Integer) - Optional - The length of time for which a TOTP code will be valid, in seconds. Currently ignored by Google Authenticator. Default: 30. - **options.encoding** (String) - Optional - Key encoding (ascii, hex, base32, base64). If the key is not encoded in Base-32, it will be reencoded. Default: "ascii". ### Returns - **String** - A URL suitable for use with the Google Authenticator. ### Throws Error if secret or label is missing, or if hotp is used and a counter is missing, if the type is not one of `hotp` or `totp`, if the number of digits is non-numeric, or an invalid period is used. Warns if the number of digits is not either 6 or 8 (though 6 is the only one supported by Google Authenticator), and if the hashing algorithm is not one of the supported SHA1, SHA256, or SHA512. ### See https://github.com/google/google-authenticator/wiki/Key-Uri-Format ``` -------------------------------- ### HOTP window mechanics with verifyDelta and verify Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Shows how HOTP windows work: generating tokens at counters 42 and 45, then verifying with different windows. Demonstrates delta values, undefined for out-of-window, and boolean results from verify(). ```js // Set ASCII secret var secret = 'rNONHRni6BAk7y2TiKrv'; // Get HOTP counter token at counter = 42 var counter42 = speakeasy.hotp({ secret: secret, counter: 42 }); // => '566646' // Get HOTP counter token at counter = 45 var counter45 = speakeasy.hotp({ secret: secret, counter: 45 }); // => '323238' // Verify the secret at counter 42 with the actual value and a window of 10 // This will check all counter values from 42 to 52, inclusive speakeasy.hotp.verifyDelta({ secret: secret, counter: 42, token: counter42, window: 10 }); // => { delta: 0 } because the given token at counter 42 is 0 steps away from the given counter 42 // Verify the secret at counter 45, but give a counter of 42 and a window of 10 // This will check all counter values from 42 to 52, inclusive speakeasy.hotp.verifyDelta({ secret: secret, counter: 42, token: counter45, window: 10 }); // => { delta: 3 } because the given token at counter 45 is 0 steps away from given counter 42 // Not in window: specify a window of 1, which only tests counters 42 and 43, not 45 speakeasy.hotp.verifyDelta({ secret: secret, counter: 42, token: counter45, window: 1 }); // => undefined // Shortcut to use verify() to simply return whether it is verified as within the window speakeasy.hotp.verify({ secret: secret, counter: 42, token: counter45, window: 10 }); // => true // Not in window: specify a window of 1, which only tests counters 42 and 43, not 45 speakeasy.hotp.verify({ secret: secret, counter: 42, token: counter45, window: 1 }); // => false ``` -------------------------------- ### counter alias usage example Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/hotp.md Example of using speakeasy.counter to generate a token for a given secret and counter. The output is '755224'. ```javascript var speakeasy = require('speakeasy'); var token = speakeasy.counter({secret: '12345678901234567890', counter: 0}); console.log(token); // '755224' ``` -------------------------------- ### TOTP window mechanics with verifyDelta and verify Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Shows TOTP window mechanics with two-sided windows, allowing negative delta values. Generates tokens at specific times and verifies with a window of 2, demonstrating delta and boolean results. ```js var secret = 'rNONHRni6BAk7y2TiKrv'; // By way of example, we will force TOTP to return tokens at time 1453853945 and // at time 1453854005 (60 seconds ahead, or 2 steps ahead) var token1 = speakeasy.totp({ secret: secret, time: 1453853945 }); // 625175 var token3 = speakeasy.totp({ secret: secret, time: 1453854005 }); // 222636 var token2 = speakeasy.totp({ secret: secret, time: 1453854065 }); // 013052 // We can check the time at token 3, 1453853975, with token 1, but use a window of 2 // With a time step of 30 seconds, this will check all tokens from 60 seconds // before the time to 60 seconds after the time speakeasy.totp.verifyDelta({ secret: secret, token: token1, window: 2, time: 1453854005 }); // => { delta: -2 } // token is valid because because token is 60 seconds before time speakeasy.totp.verify({ secret: secret, token: token1, window: 2, time: 1453854005 }); // => true // token is valid because because token is 0 seconds before time speakeasy.totp.verify({ secret: secret, token: token3, window: 2, time: 1453854005 }); // => true // token is valid because because token is 60 seconds after time speakeasy.totp.verify({ secret: secret, token: token2, window: 2, time: 1453854005 }); // => true // This signifies that the given token, token1, is -2 steps away from // the given time, which means that it is the token for the value at // (-2 * time step) = (-2 * 30 seconds) = 60 seconds ago. ``` -------------------------------- ### hotp(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Generate a counter-based one-time token. Specify the key and counter, and receive the one-time password for that counter position as a string. ```APIDOC ## hotp(options) ### Description Generate a counter-based one-time token. Specify the key and counter, and receive the one-time password for that counter position as a string. You can also specify a token length, as well as the encoding (ASCII, hexadecimal, or base32) and the hashing algorithm to use (SHA1, SHA256, SHA512). ### Parameters - **options** (Object) - Required - Options object - **options.secret** (String) - Required - Shared secret key - **options.counter** (Integer) - Required - Counter value - **options.digest** (Buffer) - Optional - Digest, automatically generated by default - **options.digits** (Integer) - Optional (default: 6) - The number of digits for the one-time passcode. - **options.encoding** (String) - Optional (default: "ascii") - Key encoding (ascii, hex, base32, base64). - **options.algorithm** (String) - Optional (default: "sha1") - Hash algorithm (sha1, sha256, sha512). - **options.key** (String) - Optional - (DEPRECATED. Use `secret` instead.) Shared secret key - **options.length** (Integer) - Optional (default: 6) - (DEPRECATED. Use `digits` instead.) The number of digits for the one-time passcode. ### Returns - **String** - The one-time passcode. ``` -------------------------------- ### Default option assignments in index.js Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/configuration.md Shows the exact default assignments for library options as found in the source file index.js. These defaults are applied using logical OR or parseInt with fallback, so explicit falsy values like 0, NaN, or empty strings fall through to the default. ```javascript // index.js:27-30 var encoding = options.encoding || 'ascii'; var algorithm = (options.algorithm || 'sha1').toLowerCase(); // index.js:124 (hotp) var digits = (options.digits != null ? options.digits : options.length) || 6; // index.js:200-202 (hotp.verifyDelta) var digits = parseInt(options.digits, 10) || 6; var window = parseInt(options.window, 10) || 0; var counter = parseInt(options.counter, 10) || 0; // index.js:279-283 (_counter) var step = options.step || 30; var time = options.time != null ? (options.time * 1000) : Date.now(); var epoch = (options.epoch != null ? (options.epoch * 1000) : (options.initial_time * 1000)) || 0; // index.js:500-506 (generateSecret) var length = options.length || 32; var name = options.name || 'SecretKey'; var otpauth_url = options.otpauth_url != null ? options.otpauth_url : true; // index.js:625-630 (otpauthURL) var type = (options.type || 'totp').toLowerCase(); var algorithm = (options.algorithm || 'sha1').toLowerCase(); var digits = options.digits || 6; var period = options.period || 30; var encoding = options.encoding || 'ascii'; ``` -------------------------------- ### How HOTP verifyDelta works with counter and window Source: https://github.com/speakeasyjs/speakeasy/wiki/General-Usage-for-Counter-Based-Token Shows the behavior of `speakeasy.hotp.verifyDelta` and `speakeasy.hotp.verify` with different counter values and windows. It demonstrates that a window of 10 checks counters 42 to 52 inclusive, and a window of 1 only checks 42 and 43. The `verify` method returns a boolean instead of a delta object. ```javascript // Set ASCII secret var secret = 'rNONHRni6BAk7y2TiKrv'; // Get HOTP counter token at counter = 42 var counter42 = speakeasy.hotp({ secret: secret, counter: 42 }); // => '566646' // Get HOTP counter token at counter = 45 var counter45 = speakeasy.hotp({ secret: secret, counter: 45 }); // => '323238' // Verify the secret at counter 42 with the actual value and a window of 10 // This will check all counter values from 42 to 52, inclusive speakeasy.hotp.verifyDelta({ secret: secret, counter: 42, token: counter42, window: 10 }); // => { delta: 0 } because the given token at counter 42 is 0 steps away from // the given counter 42 // Verify the secret at counter 45, but give a counter of 42 and a window of 10 // This will check all counter values from 42 to 52, inclusive speakeasy.hotp.verifyDelta({ secret: secret, counter: 42, token: counter45, window: 10 }); // => { delta: 3 } because the given token at counter 45 is 0 steps away from // given counter 42 // Not in window: specify a window of 1, which only tests counters 42 and 43, // not 45 speakeasy.hotp.verifyDelta({ secret: secret, counter: 42, token: counter45, window: 1 }); // => undefined // Shortcut to use verify() to simply return whether it is verified as within // the window speakeasy.hotp.verify({ secret: secret, counter: 42, token: counter45, window: 10 }); // => true // Not in window: specify a window of 1, which only tests counters 42 and 43, // not 45 speakeasy.hotp.verify({ secret: secret, counter: 42, token: counter45, window: 1 }); // => false ``` -------------------------------- ### hotp.verifyDelta(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/configuration.md Verifies a token and returns the delta (difference) between the provided counter and the matching counter, or null if not found. ```APIDOC ## hotp.verifyDelta(options) ### Description Verifies a token and returns the delta (difference) between the provided counter and the matching counter, or null if not found. ### Method Function ### Parameters #### Options Object - **secret** (String | Buffer) - Required - Shared secret key. - **counter** (Integer) - Required - Counter value. - **token** (String) - Required - Passcode to validate. - **digits** (Integer) - Optional - Number of passcode digits. Default: `6`. - **window** (Integer) - Optional - Verification leeway (one-sided: `C` .. `C + W`). Default: `0`. - **encoding** (String) - Optional - Key encoding: `ascii`, `hex`, `base32`, `base64`. Default: `'ascii'`. - **algorithm** (String) - Optional - Hash algorithm: `sha1`, `sha256`, `sha512`. Default: `'sha1'`. ### Response Returns an integer delta or null if no match found. ``` -------------------------------- ### totp(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Generate a time-based one-time token. ```APIDOC ## totp(options) ### Description Generate a time-based one-time token. ### Parameters - **options** (Object) - Required - Options object - **options.secret** (String) - Required - Shared secret key - **options.time** (Integer) - Optional - Time in seconds since epoch (default: current time) - **options.digits** (Integer) - Optional (default: 6) - The number of digits for the one-time passcode. - **options.encoding** (String) - Optional (default: "ascii") - Key encoding (ascii, hex, base32, base64). - **options.algorithm** (String) - Optional (default: "sha1") - Hash algorithm (sha1, sha256, sha512). - **options.step** (Integer) - Optional (default: 30) - Time step in seconds. - **options.key** (String) - Optional - (DEPRECATED. Use `secret` instead.) Shared secret key ### Returns - **String** - The one-time passcode. ``` -------------------------------- ### Get a time-based token for the current time Source: https://github.com/speakeasyjs/speakeasy/wiki/General-Usage-for-Time-Based-Token Generate a TOTP token using the base-32 secret. HOTP can be used by replacing totp with hotp and providing a counter. ```javascript // 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 ``` -------------------------------- ### Require speakeasy module Source: https://github.com/speakeasyjs/speakeasy/wiki/General-Usage-for-Counter-Based-Token Loads the speakeasy library for counter-based token generation and verification. ```javascript var speakeasy = require("speakeasy"); ``` -------------------------------- ### Use _counter to compute counter value Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/totp.md Example usage of speakeasy._counter with time in seconds, step 30, and epoch 0. Outputs the counter value 37037036. ```javascript var speakeasy = require('speakeasy'); var counter = speakeasy._counter({ time: 1111111109, // seconds step: 30, epoch: 0 }); console.log(counter); // 37037036 ``` -------------------------------- ### hotp.verifyDelta(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/errors.md Verifies an HOTP token and returns the delta. Throws errors when required options are missing. ```APIDOC ## hotp.verifyDelta(options) ### Description Verifies an HOTP token and returns the delta. Throws errors when required options are missing. ### Errors - `Speakeasy - hotp.verifyDelta - Missing secret` - Triggered when `options.secret` is null/undefined. - `Speakeasy - hotp.verifyDelta - Missing token` - Triggered when `options.token` is null/undefined. ``` -------------------------------- ### Non-default encoding, algorithm, and pre-built secret Buffer Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/digest.md Shows using base32 encoding with sha256, and passing a Buffer to bypass encoding handling. The Buffer example uses sha512. ```javascript var speakeasy = require('speakeasy'); var digest = speakeasy.digest({ secret: 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', // base32 of 12345678901234567890 counter: 4, encoding: 'base32', algorithm: 'sha256' }); // Passing a Buffer bypasses encoding handling entirely var fromBuffer = speakeasy.digest({ secret: Buffer.from('12345678901234567890'), counter: 4, algorithm: 'sha512' }); ``` -------------------------------- ### hotp.verify(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Verify a counter-based one-time token against the secret and return true if it verifies. ```APIDOC ## hotp.verify(options) ### Description Verify a counter-based one-time token against the secret and return true if it verifies. ### Parameters - **options** (Object) - Required - Options object - **options.secret** (String) - Required - Shared secret key - **options.token** (String) - Required - The token to verify - **options.counter** (Integer) - Required - Counter value - **options.digits** (Integer) - Optional (default: 6) - The number of digits for the one-time passcode. - **options.encoding** (String) - Optional (default: "ascii") - Key encoding (ascii, hex, base32, base64). - **options.algorithm** (String) - Optional (default: "sha1") - Hash algorithm (sha1, sha256, sha512). - **options.window** (Integer) - Optional (default: 0) - Allowed clock drift in steps. ### Returns - **Boolean** - True if the token verifies, false otherwise. ``` -------------------------------- ### totp.verifyDelta(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Verify a time-based one-time token against the secret and return the delta. ```APIDOC ## totp.verifyDelta(options) ### Description Verify a time-based one-time token against the secret and return the delta. ### Parameters - **options** (Object) - Required - Options object - **options.secret** (String) - Required - Shared secret key - **options.token** (String) - Required - The token to verify - **options.time** (Integer) - Optional - Time in seconds since epoch (default: current time) - **options.digits** (Integer) - Optional (default: 6) - The number of digits for the one-time passcode. - **options.encoding** (String) - Optional (default: "ascii") - Key encoding (ascii, hex, base32, base64). - **options.algorithm** (String) - Optional (default: "sha1") - Hash algorithm (sha1, sha256, sha512). - **options.step** (Integer) - Optional (default: 30) - Time step in seconds. - **options.window** (Integer) - Optional (default: 0) - Allowed clock drift in steps. ### Returns - **Object** - The delta object (e.g., {delta: 0}) or null if invalid. ``` -------------------------------- ### otpauthURL(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/index.md Builds a Google Authenticator `otpauth://` URL from the provided options. ```APIDOC ## otpauthURL(options) ### Description Builds a Google Authenticator `otpauth://` URL from the provided options. ### Method Function ### Signature `otpauthURL(options)` ### Parameters - **options** (object) - Required - Options for the URL. - **secret** (string) - Required - The base32-encoded secret. - **label** (string) - Required - The label for the account. - **issuer** (string) - Optional - The issuer name. - **algorithm** (string) - Optional - The HMAC algorithm (default: 'sha1'). - **digits** (number) - Optional - The number of digits (default: 6). - **period** (number) - Optional - The time step in seconds (default: 30). - **type** (string) - Optional - The OTP type ('hotp' or 'totp', default: 'totp'). - **counter** (number) - Optional - The counter value for HOTP. ### Returns - **string** - The otpauth URL. ``` -------------------------------- ### Catching Speakeasy errors in consumer code Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/errors.md All library errors are synchronous Error instances; catch by evaluating e.message or with a broad try/catch. The example shows a generic catch-all, branching on the message prefix, and checking verification return values instead of exceptions. ```javascript var speakeasy = require('speakeasy'); // 1. Generic catch-all try { var token = speakeasy.hotp({secret: 'abc'}); // counter missing } catch (e) { console.error(e.message); // 'Speakeasy - hotp - Missing counter' } // 2. Branching on the message prefix try { speakeasy.otpauthURL({type: 'foo', secret: 's', label: 'l'}); } catch (e) { if (e.message.indexOf('Speakeasy - otpauthURL - Invalid type') === 0) { // handle invalid type } else { throw e; } } // 3. Verification failures are not exceptions — check the return value var ok = speakeasy.totp.verify({secret: 'abc', token: '000000'}); if (!ok) { /* token invalid or outside window */ } ``` -------------------------------- ### generateSecretASCII([length], [symbols]) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Generates a key of a certain length (default 32) from A-Z, a-z, 0-9, and symbols (if requested). ```APIDOC ## generateSecretASCII([length], [symbols]) ### Description Generates a key of a certain length (default 32) from A-Z, a-z, 0-9, and symbols (if requested). ### Parameters - **length** (Integer) - Optional (default: 32) - Length of the key. - **symbols** (Boolean) - Optional (default: false) - Whether to include symbols. ### Returns - **String** - The generated key. ``` -------------------------------- ### generateSecretASCII([length], [symbols]) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Generates a key of a certain length (default 32) from A-Z, a-z, 0-9, and symbols (if requested). ```APIDOC ## generateSecretASCII([length], [symbols]) ### Description Generates a key of a certain length (default 32) from A-Z, a-z, 0-9, and symbols (if requested). ### Method Function call ### Parameters - **length** (Integer) - Optional - The length of the key. Defaults to 32. - **symbols** (Boolean) - Optional - Whether to include symbols in the key. Defaults to false. ### Returns - **String** - The generated key. ``` -------------------------------- ### TOTP window verification with forced times and delta/boolean results Source: https://github.com/speakeasyjs/speakeasy/wiki/General-Usage-for-Time-Based-Token Demonstrates TOTP window mechanics with forced times. Generates tokens at specific times, then verifies them with a window of 2, showing negative delta for past tokens and boolean results for valid tokens within the window. ```javascript var secret = 'rNONHRni6BAk7y2TiKrv'; // By way of example, we will force TOTP to return tokens at time 1453853945 // and at time 1453854005 (60 seconds ahead, or 2 steps ahead) var token1 = speakeasy.totp({ secret: secret, time: 1453853945 }); // 625175 var token3 = speakeasy.totp({ secret: secret, time: 1453854005 }); // 222636 var token2 = speakeasy.totp({ secret: secret, time: 1453854065 }); // 013052 // We can check the time at token 3, 1453853975, with token 1, but use a window // of 2 With a time step of 30 seconds, this will check all tokens from 60 // seconds before the time to 60 seconds after the time speakeasy.totp.verifyDelta({ secret: secret, token: token1, window: 2, time: 1453854005 }); // => { delta: -2 } // token is valid because because token is 60 seconds before time speakeasy.totp.verify({ secret: secret, token: token1, window: 2, time: 1453854005 }); // => true // token is valid because because token is 0 seconds before time speakeasy.totp.verify({ secret: secret, token: token3, window: 2, time: 1453854005 }); // => true // token is valid because because token is 60 seconds after time speakeasy.totp.verify({ secret: secret, token: token2, window: 2, time: 1453854005 }); // This signifies that the given token, token1, is -2 steps away from // the given time, which means that it is the token for the value at // (-2 * time step) = (-2 * 30 seconds) = 60 seconds ago. ``` -------------------------------- ### Generate QR code data URL Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Uses the qrcode package to generate a PNG data URL from secret.otpauth_url for displaying in an tag. ```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(''); }); ``` -------------------------------- ### otpauthURL(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Generate an URL for use with the Google Authenticator app. ```APIDOC ## otpauthURL(options) ### Description Generate an URL for use with the Google Authenticator app. ### Parameters - **options** (Object) - Required - Options object - **options.secret** (String) - Required - Shared secret key - **options.label** (String) - Required - Label for the authenticator entry. - **options.type** (String) - Optional (default: "totp") - Type of OTP (hotp or totp). - **options.counter** (Integer) - Optional - Counter value (required for hotp). - **options.issuer** (String) - Optional - Issuer for the authenticator entry. - **options.algorithm** (String) - Optional (default: "sha1") - Hash algorithm (sha1, sha256, sha512). - **options.digits** (Integer) - Optional (default: 6) - The number of digits for the one-time passcode. - **options.period** (Integer) - Optional (default: 30) - Time step in seconds (for totp). ### Returns - **String** - The otpauth URL. ``` -------------------------------- ### Generate a secret key Source: https://github.com/speakeasyjs/speakeasy/wiki/General-Usage-for-Counter-Based-Token Generates a 20-character secret key. Access the key using secret.ascii, secret.hex, or secret.base32. ```javascript // Generate a secret key. var secret = speakeasy.generateSecret({length: 20}); // secret key is 20 characters long // Access using secret.ascii, secret.hex, or secret.base32. ``` -------------------------------- ### otpauthURL(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/errors.md Generates an otpauth:// URL. Throws errors for invalid or missing parameters. ```APIDOC ## otpauthURL(options) ### Description Generates an otpauth:// URL. Throws errors for invalid or missing parameters. ### Errors - `Speakeasy - otpauthURL - Invalid type \`\`; must be \`hotp\` or \`totp\`` - Triggered when `options.type` lowercases to neither 'hotp' nor 'totp'. - `Speakeasy - otpauthURL - Missing secret` - Triggered when `options.secret` is falsy. - `Speakeasy - otpauthURL - Missing label` - Triggered when `options.label` is falsy. - `Speakeasy - otpauthURL - Missing counter value for HOTP` - Triggered when `type === 'hotp'` and `options.counter` is null/undefined. - `Speakeasy - otpauthURL - Invalid digits \`\`` - Triggered when `options.digits` is non-null and `isNaN(digits)` is true. - `Speakeasy - otpauthURL - Invalid period \`\`` - Triggered when `options.period` is non-null and non-integer. ``` -------------------------------- ### hotp(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/errors.md Generates an HMAC-based one-time password. Throws errors when required options are missing. ```APIDOC ## hotp(options) ### Description Generates an HMAC-based one-time password. Throws errors when required options are missing. ### Errors - `Speakeasy - hotp - Missing secret` - Triggered when both `options.secret` and deprecated `options.key` are null/undefined. - `Speakeasy - hotp - Missing counter` - Triggered when `options.counter` is null/undefined. ``` -------------------------------- ### generate_key(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/index.md Deprecated alias for `generateSecret`. Use `generateSecret` instead. ```APIDOC ## generate_key(options) ### Description Deprecated alias for `generateSecret`. Use `generateSecret` instead. ### Method Function ### Signature `generate_key(options)` ### Parameters - **options** (object) - Optional - Same as `generateSecret`. ### Returns - **object** - A `GeneratedSecret` object. ``` -------------------------------- ### totp.verify(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Verify a time-based one-time token against the secret and return true if it verifies. ```APIDOC ## totp.verify(options) ### Description Verify a time-based one-time token against the secret and return true if it verifies. ### Parameters - **options** (Object) - Required - Options object - **options.secret** (String) - Required - Shared secret key - **options.token** (String) - Required - The token to verify - **options.time** (Integer) - Optional - Time in seconds since epoch (default: current time) - **options.digits** (Integer) - Optional (default: 6) - The number of digits for the one-time passcode. - **options.encoding** (String) - Optional (default: "ascii") - Key encoding (ascii, hex, base32, base64). - **options.algorithm** (String) - Optional (default: "sha1") - Hash algorithm (sha1, sha256, sha512). - **options.step** (Integer) - Optional (default: 30) - Time step in seconds. - **options.window** (Integer) - Optional (default: 0) - Allowed clock drift in steps. ### Returns - **Boolean** - True if the token verifies, false otherwise. ``` -------------------------------- ### hotp.verify(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Verifies a counter-based one-time token against the secret and returns true if it verifies. Helper function for `hotp.verifyDelta()` that returns a boolean instead of an object. ```APIDOC ## hotp.verify(options) ### Description Verifies a counter-based one-time token against the secret and returns true if it verifies. Helper function for `hotp.verifyDelta()` that returns a boolean instead of an object. ### Method Function call ### Parameters #### options (Object) - Required - **secret** (String) - Required - Shared secret key - **token** (String) - Required - Passcode to validate - **counter** (Integer) - Required - Counter value. This should be stored by the application and must be incremented for each request. - **digits** (Integer) - Optional, default: 6 - The number of digits for the one-time passcode. - **window** (Integer) - Optional, default: 0 - The allowable margin for the counter. The function will check "W" codes in the future against the provided passcode, e.g. if W = 10, and C = 5, this function will check the passcode against all One Time Passcodes between 5 and 15, inclusive. - **encoding** (String) - Optional, default: "ascii" - Key encoding (ascii, hex, base32, base64). - **algorithm** (String) - Optional, default: "sha1" - Hash algorithm (sha1, sha256, sha512). ### Returns - **Boolean** - Returns true if the token matches within the given window, false otherwise. ``` -------------------------------- ### Verify with negative delta for clock skew Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/totp.md Shows how a two-sided window reveals a negative delta when the server clock is one step ahead of token generation. With time 89 (counter 2) and window 4, the token generated at counter 1 is found, resulting in a delta of -1. ```javascript var speakeasy = require('speakeasy'); var token = speakeasy.totp({secret: '12345678901234567890', time: 59}); // time 59 → counter 1 (Math.floor(59 / 30)) var result = speakeasy.totp.verifyDelta({ secret: '12345678901234567890', token: token, time: 89, // counter 2 — verify clock one step ahead of generation window: 4 // search counters 2-4 = -2 .. 2+4 = 6 (two-sided) }); // Found at counter 1: hotp delta = 1 - (-2) = 3; totp delta = 3 - 4 = -1 console.log(result); // { delta: -1 } ``` -------------------------------- ### HOTP error handling for missing counter and secret Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/hotp.md Shows the errors thrown when required options are missing. Missing counter yields 'Speakeasy - hotp - Missing counter'; missing secret (and deprecated key) yields 'Speakeasy - hotp - Missing secret'. ```javascript var speakeasy = require('speakeasy'); try { speakeasy.hotp({secret: 'abc'}); // counter missing } catch (e) { console.log(e.message); // 'Speakeasy - hotp - Missing counter' } try { speakeasy.hotp({counter: 1}); // secret (and deprecated key) missing } catch (e) { console.log(e.message); // 'Speakeasy - hotp - Missing secret' } ``` -------------------------------- ### totp.verify(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Verifies a time-based one-time token against the secret and returns a boolean indicating whether the token is valid within the given window. This is a helper function for verifyDelta() that returns a boolean instead of an object. ```APIDOC ## totp.verify(options) ### Description Verifies a time-based one-time token against the secret and returns true if it verifies. This is a helper function for verifyDelta() that returns a boolean instead of an object. ### Method Function call ### Parameters #### options (Object) - Required - **secret** (String) - Required - Shared secret key - **token** (String) - Required - Passcode to validate - **time** (Integer) - Optional - Time in seconds with which to calculate counter value. Defaults to `Date.now()`. - **step** (Integer) - Optional - Time step in seconds. Defaults to 30. - **epoch** (Integer) - Optional - Initial time since the UNIX epoch from which to calculate the counter value. Defaults to 0 (no offset). - **counter** (Integer) - Optional - Counter value, calculated by default. - **digits** (Integer) - Optional - The number of digits for the one-time passcode. Defaults to 6. - **window** (Integer) - Optional - The allowable margin for the counter. The function will check "W" codes in the future and the past against the provided passcode, e.g. if W = 5, and C = 1000, this function will check the passcode against all One Time Passcodes between 995 and 1005, inclusive. Defaults to 0. - **encoding** (String) - Optional - Key encoding (ascii, hex, base32, base64). Defaults to "ascii". - **algorithm** (String) - Optional - Hash algorithm (sha1, sha256, sha512). Defaults to "sha1". ### Returns - **Boolean** - Returns true if the token matches within the given window, false otherwise. ``` -------------------------------- ### generate_key_ascii(length, symbols) Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/api-reference/index.md Deprecated alias for `generateSecretASCII`. Use `generateSecretASCII` instead. ```APIDOC ## generate_key_ascii(length, symbols) ### Description Deprecated alias for `generateSecretASCII`. Use `generateSecretASCII` instead. ### Method Function ### Signature `generate_key_ascii(length, symbols)` ### Parameters - **length** (number) - Optional - The length of the key (default: 32). - **symbols** (boolean) - Optional - Whether to include symbols (default: false). ### Returns - **string** - The generated ASCII key. ``` -------------------------------- ### Calculate a counter-based token Source: https://github.com/speakeasyjs/speakeasy/blob/master/README.md Generate and verify an HOTP token using a counter value. ```javascript // 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 }); ``` -------------------------------- ### totp.verifyDelta(options) Source: https://github.com/speakeasyjs/speakeasy/blob/master/_autodocs/errors.md Verifies a TOTP token and returns the delta. Throws errors when required options are missing. ```APIDOC ## totp.verifyDelta(options) ### Description Verifies a TOTP token and returns the delta. Throws errors when required options are missing. ### Errors - `Speakeasy - totp.verifyDelta - Missing secret` - Triggered when `options.secret` is null/undefined. - `Speakeasy - totp.verifyDelta - Missing token` - Triggered when `options.token` is null/undefined. ```