A complete Authy client with support for TOTP, OneTouch, Phone Verification and Phone Intelligence APIs.
Install the package via yarn
:
yarn add authy-client
or via npm
:
npm install authy-client --save
The following is a complete example of registering a user and requesting an SMS using any of the three possible async APIs offered by this package.
import { Client } from 'authy-client';
const client = new Client({ key: 'foo' });
(async function() {
const { user: { id: authyId } } = await client.registerUser({
countryCode: 'PT',
email: '[email protected]',
phone: '911234567' }
);
const { cellphone } = await client.requestSms({ authyId });
console.log(`SMS requested to ${cellphone}`)
}());
const Client = require('authy-client').Client;
const client = new Client({ key: 'foo' });
client.registerUser({
countryCode: 'PT',
email: '[email protected]',
phone: '911234567'
}).then(function(response) {
return response.user.id;
}).then(function(authyId) {
return client.requestSms({ authyId: authyId });
}).then(function(response) {
console.log(`SMS requested to ${response.cellphone}`);
});
const Client = require('authy-client').Client;
const client = new Client({ key: 'foo' });
client.registerUser({
countryCode: 'PT',
email: '[email protected]',
phone: '911234567'
}, function(err, res) {
if (err) throw err;
client.requestSms({ authyId: res.user.id }, function(err, res) {
if (err) throw err;
console.log(`SMS requested to ${res.cellphone}`)
});
});
If you want to run this example without first transpiling it, you can install the babel-cli
package and run node_modules/.bin/babel-node example.js
.
Another option of interacting with Authy's API is by using the available command-line interface (cli). It handles most tasks without require any coding.
❯ authy
Commands:
activity <command> Manage activity
application <command> Manage application information
onetouch <command> Manage onetouch requests
phone <command> Manage phone verifications
user <command> Manage users
Options:
--key API Key [string] [required]
--pretty Whether to print pretty results [boolean] [default: true]
--help Show help [boolean]
Note that all calls must be authenticated using the API Key. However, if you prefer, you can define the API Key using the environment variable AUTHY_KEY
such as:
❯ AUTHY_KEY=foobar authy <command>
args
(Object): the required arguments object.args.key
(string): The private API key obtained from the Authy Dashboard.[options]
(Object): The options object.[options.host=https://api.authy.com]
(string): The target API endpoint.[options.timeout=5000]
(number): The maximum request time, in milliseconds.
new Client({ key: 'foo' }, { timeout: 10000 });
Authy TOTP (Time-based One-time Password) is an API that allows application developers to enable two-factor authentication (2FA) for a user. 2FA, as the name suggests, is an additional step to secure an user's account or action by comparing a code generated or sent to the user's mobile phone against a shared secret.
Create an Authy user based on the users mobile phone number and email. The returned Authy Id should be stored on your database for subsequent calls.
The library automatically converts conforming country codes (e.g. US
) to the corresponding country calling code (e.g. 1
) and validates the resulting phone number thoroughly before submitting it to Authy.
args
(Object): the required arguments object.args.countryCode
(string): the user's phone country code in ISO 3166 alpha 2 format (recommended format, e.g.US
) or a numeric country calling code (use at your own risk).args.email
(string): the user's email address.args.phone
(string): the user's phone number.[callback]
(Function): a callback, otherwise a Promise is returned.
const { user: { id: authyId } } = await client.registerUser({ countryCode: 'PT', email: '[email protected]', phone: '911234567' });
console.log('Authy Id', authyId);
client.registerUser({ countryCode: 'PT', email: '[email protected]', phone: '911234567' })
.then(function(response) {
console.log('Authy Id', response.user.id);
})
.catch(function(error) {
throw error;
});
client.registerUser({ countryCode: 'PT', email: '[email protected]', phone: '911234567' }, function(err, res) {
if (err) throw err;
console.log('Authy Id', res.user.id);
});
❯ AUTHY_KEY=foobar authy user create 911234567 PT [email protected]
Request an SMS with a token for users that don't own a smartphone. If the Authy app is in use by the user, this request is ignored and a push notification is sent instead.
args
(Object): the required arguments object.args.authyId
(string): the user's Authy Id.[options]
(Object): the options object.[options.action]
(string): the action or context that is being validated.[options.force]
(boolean): whether to send an SMS even if the user is using the mobile application.[options.message]
(string): a message for the specific action, if one is set.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.requestSms({ authyId: 1635 });
console.log('Message sent successfully to', response.cellphone);
client.requestSms({ authyId: 1635 })
.then(function(response) {
console.log('Message sent successfully to', response.cellphone);
})
.catch(function(error) {
throw error;
});
client.requestSms({ authyId: 1635 }, function(err, res) {
if (err) throw err;
console.log('Message sent successfully to', res.cellphone);
});
❯ AUTHY_KEY=foobar authy user request sms 1635
Request a call with a token for users that don't own a smartphone. If the Authy app is in use by the user, this request is ignored and a push notification is sent instead.
args
(Object): the required arguments object.args.authyId
(string): the user's Authy Id.[options]
(Object): the options object.[options.action]
(string): the action or context that is being validated.[options.force]
(boolean): whether to call the user even if the mobile application is in use.[options.message]
(string): a message for the specific action, if one is set.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.requestCall({ authyId: 1635 });
console.log('Call requested successfully to', response.cellphone);
client.requestCall({ authyId: 1635 })
.then(function(response) {
console.log('Call requested successfully to', response.cellphone);
})
.catch(function(error) {
throw error;
});
client.requestCall({ authyId: 1635 }, function(err, res) {
if (err) throw err;
console.log('Call requested successfully to', res.cellphone);
});
❯ AUTHY_KEY=foobar authy user request call 1635
Verify if a token submitted by the user is valid or not.
args
(Object): the required arguments object.args.authyId
(string): the user's Authy Id.args.token
(string): the token to verify.[options]
(Object): the options object.[options.force]
(boolean): whether to verify the token regardless of the user's login status.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.verifyToken({ authyId: 1635, token: '1234567' });
console.log('Token is valid');
client.verifyToken({ authyId: 1635, token: '1234567' })
.then(function(response) {
console.log('Token is valid');
})
.catch(function(error) {
throw error;
});
client.verifyToken({ authyId: 1635, token: '1234567' }, function(err, res) {
if (err) throw err;
console.log('Token is valid');
});
❯ AUTHY_KEY=foobar authy user verify --token 1234567
Delete a user from the application.
args
(Object): the required arguments object.args.authyId
(string): the user's Authy Id.[options]
(Object): the options object.[options.ip]
(string): the IP requesting to delete the user.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.deleteUser({ authyId: 1635 });
console.log('User has been scheduled for deletion');
client.deleteUser({ authyId: 1635 })
.then(function(response) {
console.log('User has been scheduled for deletion');
})
.catch(function(error) {
throw error;
});
client.deleteUser({ authyId: 1635 }, function(err, res) {
if (err) throw err;
console.log('User has been scheduled for deletion');
});
❯ AUTHY_KEY=foobar authy user delete 1635
Register a user activity.
args
(Object): the required arguments object.args.authyId
(string): the user's Authy Id.args.type
(string): the activity type (one ofpassword_reset
,banned
,unbanned
orcookie_login
).[data]
(Object): a data object associated with the activity.[options]
(Object): the options object.[options.ip]
(string): the IP of the user registering the activity.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.registerActivity({ authyId: 1635, data: { reason: 'foo' }, type: 'banned' }, { ip: '127.0.0.1' });
console.log('Activity registered');
client.registerActivity({ authyId: 1635, data: { reason: 'foo' }, type: 'banned' }, { ip: '127.0.0.1' })
.then(function(response) {
console.log('Activity registered');
})
.catch(function(error) {
throw error;
});
client.registerActivity({ authyId: 1635, data: { reason: 'foo' }, type: 'banned' }, { ip: '127.0.0.1' }, function(err, res) {
if (err) throw err;
console.log('Activity registered');
});
❯ AUTHY_KEY=foobar authy activity create 1635 \
--data.reason foo \
--type banned \
--ip 127.0.0.1
Retrieve the user status, such as the registered country code, phone number, devices and confirmation status.
args
(Object): the required arguments object.args.authyId
(string): the user's Authy Id.[options]
(Object): the options object.[options.ip]
(string): the IP of the user requesting to see the user details.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.getUserStatus({ authyId: 1635 });
console.log('User status', response.status);
client.getUserStatus({ authyId: 1635 })
.then(function(response) {
console.log('User status', response.status);
})
.catch(function(error) {
throw error;
});
client.getUserStatus({ authyId: 1635 }, function(err, res) {
if (err) throw err;
console.log('User status', response.status);
});
❯ AUTHY_KEY=foobar authy user get status 1635
Retrieve application details such as its name or current billing plan.
[options]
(Object): the options object.[options.ip]
(string): the IP of the user requesting to see the application details.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.getApplicationDetails();
console.log('Application details', response.app);
client.getApplicationDetails()
.then(function(response) {
console.log('Application details', response.app);
})
.catch(function(error) {
throw error;
});
client.getApplicationDetails(function(err, res) {
if (err) throw err;
console.log('Application details', response.app);
});
❯ AUTHY_KEY=foobar authy application get details
Retrieve application statistics by month and current quotas.
[options]
(Object): the options object.[options.ip]
(string): the IP of the user requesting to see the application statistics.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.getApplicationStatistics();
console.log('Application statistics', response);
client.getApplicationStatistics()
.then(function(response) {
console.log('Application statistics', response);
})
.catch(function(error) {
throw error;
});
client.getApplicationStatistics(function(err, res) {
if (err) throw err;
console.log('Application statistics', response);
});
❯ AUTHY_KEY=foobar authy application get statistics
The Phone Verification API allows for a simple phone verification for situations where the complexity of the TOTP API is not required. First, a code is sent to the user's phone number and then that code is submitted back by the user. Authy verifies that the code matches the one issued for it.
Verify a phone number by sending it a verification code by SMS or call. Custom messages for the SMS are currently not working so support has not been added.
args
(Object): the required arguments object.args.countryCode
(string): the user's phone country code in ISO 3166 alpha 2 format (recommended format, e.g.US
) or a numeric country calling code (use at your own risk).args.phone
(string): the user's phone number to verify.args.via
(string): the mechanism used to send the verification code (sms
orcall
).[options]
(Object): the options object.[options.locale]
(string): the locale of the message received by the user. If none is given, Authy will attempt to auto-detect it based on the country code passed, otherwise English will be used.[callback]
(Function): a callback, otherwise a Promise is returned.
import { enums } from 'authy-client';
const response = await client.startPhoneVerification({ countryCode: 'US', locale: 'en', phone: '7754615609', via: enums.verificationVia.SMS });
console.log('Phone information', response);
const enums = require('authy-client').enums;
client.startPhoneVerification({ countryCode: 'US', locale: 'en', phone: '7754615609', via: enums.verificationVia.SMS })
.then(function(response) {
console.log('Phone information', response);
})
.catch(function(error) {
throw error;
});
const enums = require('authy-client').enums;
client.startPhoneVerification({ countryCode: 'US', locale: 'en', phone: '7754615609', via: enums.verificationVia.SMS }, function(err, res) {
if (err) throw err;
console.log('Phone information', response);
});
❯ AUTHY_KEY=foobar authy phone verify 7754615609 US \
--locale=en \
--via=sms
Verify a phone number through a verification code.
args
(Object): the required arguments object.args.countryCode
(string): the user's phone country code in ISO 3166 alpha 2 format (recommended format, e.g.US
) or a numeric country calling code (use at your own risk).args.phone
(string): the user's phone number to verify.args.token
(string): the token submitted by the user to verify the phone.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.verifyPhone({ countryCode: 'US', phone: '7754615609', token: '1234' });
console.log('Verification code is correct');
client.verifyPhone({ countryCode: 'US', phone: '7754615609', token: '1234' })
.then(function(response) {
console.log('Verification code is correct');
})
.catch(function(error) {
throw error;
});
client.verifyPhone({ countryCode: 'US', phone: '7754615609', token: '1234' }, function(err, res) {
if (err) throw err;
console.log('Verification code is correct');
});
❯ AUTHY_KEY=foobar authy phone verify 7754615609 US --token 1234
The Phone Intelligence API allows an application developer to retrieve information about a specific number such as its type (VoIP, landline or mobile) and carrier.
Verify a phone number by sending it a verification code by SMS or call. Custom messages for the SMS are currently not working so support has not been added.
args
(Object): the required arguments object.args.countryCode
(string): the phone's country code in ISO 3166 alpha 2 format (recommended format, e.g.US
) or a numeric country calling code (use at your own risk).args.phone
(string): the phone's number to retrieve information about.[options]
(Object): the options object.[options.ip]
(string): the IP of the user requesting to retrieve information about the phone.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.getPhoneInformation({ countryCode: 'US', phone: '7754615609' });
console.log('Phone information', response);
client.getPhoneInformation({ countryCode: 'US', phone: '7754615609' })
.then(function(response) {
console.log('Phone information', response);
})
.catch(function(error) {
throw error;
});
client.getPhoneInformation({ countryCode: 'US', phone: '7754615609' }, function(err, res) {
if (err) throw err;
console.log('Phone information', response);
});
❯ AUTHY_KEY=foobar authy phone get information 7754615609 US
Authy OneTouch is an API that allows application developers to create simple approval requests so that users can frictionless approve or deny such request. It can be used for a variety of purposes, such as authentication (e.g. login approval) or validation (e.g. financial transaction approval).
When the user takes actions, Authy sends a GET or POST callback to a URL defined on the application dashboard. The request, which can optionally be cryptographically verified, allows for immediate reaction. An alternate polling method can also be used.
Create an approval request for the given Authy Id and send it to the user as a push notification.
args
(Object): the required arguments object.args.authyId
(string): the user's Authy Id.args.message
(string): the message shown to the user upon receiving the approval request.[details]
(Object): the details object.[details.hidden]
(Object): a dictionary of hidden details associated with the approval request.[details.visible]
(Object): a dictionary of visible details associated with the approval request.[logos]
(array): the custom logos collection.[logos.<n>]
(Object): a custom logo object.[logos.<n>.res]
(string): the target resolution of the custom logo (one ofdefault
,low
,med
orhigh
).[logos.<n>.url]
(string): the url of the custom logo image.[options]
(Object): the options object.[options.ttl]
(integer): the number of seconds that the approval request will be available for being responded. If set to0
, the approval request won't expire.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.createApprovalRequest({
authyId: 1635,
details: {
hidden: {
ip_address: '10.10.3.203'
},
visible: {
'Account Number': '981266321',
location: 'California, USA',
username: 'Bill Smith'
}
},
logos: [{
res: 'default',
url: 'https://example.com/logos/default.png'
}, {
res: 'low',
url: 'https://example.com/logos/low.png'
}],
message: 'Login requested for a CapTrade Bank account.',
}, {
ttl: 120
});
console.log('Approval request UUID', response.approval_request.uuid);
client.createApprovalRequest({
authyId: 1635,
details: {
hidden: {
ip_address: '10.10.3.203'
},
visible: {
'Account Number': '981266321',
location: 'California, USA',
username: 'Bill Smith'
}
},
logos: [{
res: 'default',
url: 'https://example.com/logos/default.png'
}, {
res: 'low',
url: 'https://example.com/logos/low.png'
}],
message: 'Login requested for a CapTrade Bank account.',
}, {
ttl: 120
}).then(function(response) {
console.log('Approval request UUID', response.approval_request.uuid);
}).catch(function(error) {
throw error;
});
client.createApprovalRequest({
authyId: 1635,
details: {
hidden: {
ip_address: '10.10.3.203'
},
visible: {
'Account Number': '981266321',
location: 'California, USA',
username: 'Bill Smith'
}
},
logos: [{
res: 'default',
url: 'https://example.com/logos/default.png'
}, {
res: 'low',
url: 'https://example.com/logos/low.png'
}],
message: 'Login requested for a CapTrade Bank account.',
}, {
ttl: 120
}, function(err, res) {
if (err) throw err;
console.log('Approval request UUID', response.approval_request.uuid);
});
❯ AUTHY_KEY=foobar authy onetouch create 1635 \
'Login requested for a CapTrade Bank account.' \
--hidden.ip_address 10.10.3.203 \
--logos.0.res default \
--logos.0.url 'https://example.com/logos/default.png' \
--logos.1.res low \
--logos.1.url 'https://example.com/logos/low.png' \
--visible.'Account Number' 981266321 \
--visible.location 'California, USA' \
--visible.username 'Bill Smith' \
--ttl 120
Get information about an approval request.
args
(Object): the required arguments object.args.id
(string): the id of the approval request.[callback]
(Function): a callback, otherwise a Promise is returned.
const response = await client.getApprovalRequest({ id: '550e8400-e29b-41d4-a716-446655440000' });
console.log('Approval request', response.approval_request);
client.getApprovalRequest({ id: '550e8400-e29b-41d4-a716-446655440000' })
.then(function(response) {
console.log('Approval request', response.approval_request);
})
.catch(function(error) {
throw error;
});
client.getApprovalRequest({ id: '550e8400-e29b-41d4-a716-446655440000' }, function(err, res) {
if (err) throw err;
console.log('Approval request', response.approval_request);
});
❯ AUTHY_KEY=foobar authy phone get status 550e8400-e29b-41d4-a716-446655440000
Authy callbacks contain a header (X-Authy-Signature
) with an HTTP HMAC signature of the request. This signature can be used to verify the authenticity of the request.
Currently, GET requests cannot be validated, as only POST requests contain such signature.
If you have configured your Authy application to receive callbacks for OneTouch approval requests, you should verify their authenticity.
args
(Object): the required arguments object.args.body
(Object): the parsed body of the request.args.headers
(Object): the headers of the request.args.method
(string): the method of the request (GET
orPOST
).args.protocol
(string): the protocol of the request (http
orhttps
).args.url
(string): the url of the request (e.g./callback/onetouch
).[callback]
(Function): a callback, otherwise a Promise is returned.
await client.verifyCallback({
body: {
approval_request: {
expiration_timestamp: 1455911778,
logos: null,
transaction: {
created_at_time: 1455825378,
customer_uuid: '2ccf0040-ed25-0132-5987-0e67b818e6fb',
details: {},
device_details: null,
device_geolocation: null,
device_signing_time: 0,
encrypted: false,
flagged: false,
hidden_details: {},
message: '.',
reason: null,
requester_details: null,
status: 'approved',
uuid: '996201c0-b7a7-0133-7c06-0e67b818e6fb'
}
},
authy_id: 1234567,
callback_action: 'approval_request_status',
device_uuid: '4d89c320-a9bb-0133-7c02-0e67b818e6fb',
signature: 'BObhJgZwgU7O9r4Uo9VT6j6shAOe7y/IRGpW/N0Uq34/XHZU9E+aHOI5rcQzW1ZgNCECzVrqrsnjhYEK4Zq1naKWu0YNkuvILmMz8IxJEQH+c+6x186fjIjxvP4nu4p/pfUDomo/za24s1XOjtNlVsrDTDXClHUh5MjFQbyBjhFd8gOtmGVatN7K2Lx71I8YR2JDLbRX4DlJEMu++PLBn1nqQH9tbNYzX5jjX87CXPBtDfRwfWSs/imnfZ9zkDq4ZKuBcuwzQNsxKlby6782X0o78rYhCHrcDnHgRtyMGvX9ovK3XTt6M7p6i9SKaRgBWIOFVPygxv15iJesqt9cng==',
status: 'approved',
uuid: '996221c0-b7a7-0133-7c06-0e67b818e6fb'
},
headers: {
host: 'foo.bar',
'x-authy-signature': 'hqB6las54sMBA83GKs0U1QQi9ocJ2tH20SXHZNzfqqQ=',
'x-authy-signature-nonce': 1455825429
},
method: 'POST',
protocol: 'https',
url: '/'
});
console.log('Approval request callback is valid');
client.verifyCallback({
body: {
approval_request: {
expiration_timestamp: 1455911778,
logos: null,
transaction: {
created_at_time: 1455825378,
customer_uuid: '2ccf0040-ed25-0132-5987-0e67b818e6fb',
details: {},
device_details: null,
device_geolocation: null,
device_signing_time: 0,
encrypted: false,
flagged: false,
hidden_details: {},
message: '.',
reason: null,
requester_details: null,
status: 'approved',
uuid: '996201c0-b7a7-0133-7c06-0e67b818e6fb'
}
},
authy_id: 1234567,
callback_action: 'approval_request_status',
device_uuid: '4d89c320-a9bb-0133-7c02-0e67b818e6fb',
signature: 'BObhJgZwgU7O9r4Uo9VT6j6shAOe7y/IRGpW/N0Uq34/XHZU9E+aHOI5rcQzW1ZgNCECzVrqrsnjhYEK4Zq1naKWu0YNkuvILmMz8IxJEQH+c+6x186fjIjxvP4nu4p/pfUDomo/za24s1XOjtNlVsrDTDXClHUh5MjFQbyBjhFd8gOtmGVatN7K2Lx71I8YR2JDLbRX4DlJEMu++PLBn1nqQH9tbNYzX5jjX87CXPBtDfRwfWSs/imnfZ9zkDq4ZKuBcuwzQNsxKlby6782X0o78rYhCHrcDnHgRtyMGvX9ovK3XTt6M7p6i9SKaRgBWIOFVPygxv15iJesqt9cng==',
status: 'approved',
uuid: '996221c0-b7a7-0133-7c06-0e67b818e6fb'
},
headers: {
host: 'foo.bar',
'x-authy-signature': 'hqB6las54sMBA83GKs0U1QQi9ocJ2tH20SXHZNzfqqQ=',
'x-authy-signature-nonce': 1455825429
},
method: 'POST',
protocol: 'https',
url: '/'
}).then(function(response) {
console.log('Approval request callback is valid');
})
.catch(function(error) {
throw error;
});
client.verifyCallback({
body: {
approval_request: {
expiration_timestamp: 1455911778,
logos: null,
transaction: {
created_at_time: 1455825378,
customer_uuid: '2ccf0040-ed25-0132-5987-0e67b818e6fb',
details: {},
device_details: null,
device_geolocation: null,
device_signing_time: 0,
encrypted: false,
flagged: false,
hidden_details: {},
message: '.',
reason: null,
requester_details: null,
status: 'approved',
uuid: '996201c0-b7a7-0133-7c06-0e67b818e6fb'
}
},
authy_id: 1234567,
callback_action: 'approval_request_status',
device_uuid: '4d89c320-a9bb-0133-7c02-0e67b818e6fb',
signature: 'BObhJgZwgU7O9r4Uo9VT6j6shAOe7y/IRGpW/N0Uq34/XHZU9E+aHOI5rcQzW1ZgNCECzVrqrsnjhYEK4Zq1naKWu0YNkuvILmMz8IxJEQH+c+6x186fjIjxvP4nu4p/pfUDomo/za24s1XOjtNlVsrDTDXClHUh5MjFQbyBjhFd8gOtmGVatN7K2Lx71I8YR2JDLbRX4DlJEMu++PLBn1nqQH9tbNYzX5jjX87CXPBtDfRwfWSs/imnfZ9zkDq4ZKuBcuwzQNsxKlby6782X0o78rYhCHrcDnHgRtyMGvX9ovK3XTt6M7p6i9SKaRgBWIOFVPygxv15iJesqt9cng==',
status: 'approved',
uuid: '996221c0-b7a7-0133-7c06-0e67b818e6fb'
},
headers: {
host: 'foo.bar',
'x-authy-signature': 'hqB6las54sMBA83GKs0U1QQi9ocJ2tH20SXHZNzfqqQ=',
'x-authy-signature-nonce': 1455825429
},
method: 'POST',
protocol: 'https',
url: '/'
}, function(err, res) {
if (err) throw err;
console.log('Approval request callback is valid');
});
To test using a local installation of node.js
:
npm test
To test using Docker exclusively:
docker-compose run --rm sut
npm version [<newversion> | major | minor | patch] -m "Release %s"
MIT