This article provides an overview of the SendSafely Javascript Client library for Node.js. The walk-through below includes most common SendSafely use cases, like creating a SendSafely package, sending a file to a recipient, assigning SMS authentication, setting package life (expiration), and downloading files.
The examples below assume that you installed the SendSafely JavaScript API package for Node.js so that it can be used as a CommonJS module.
- The SendSafely JavaScript API for Node.js package can be installed from the NPM Registry.
- A fully functional Node.js sample application is also published in our Github Repository and can be used as a reference when building your own application.
- Complete documentation for the JavaScript API can be found here.
Example Code
The code examples below assume that your program has been designed to accept following inputs, either from a configuration source or the user/process invoking the program:
- API Key & API Secret
- Recipient Email Address
- Recipient Mobile Phone Number
Initializing the API
The first step required to use the API is to initialize a new instance of the API using a specific set of credentials. These credentials (your API Key and API Secret) will be used by all operations invoked through the instance.
It is best practice to operate on the premise that each instance of the API you create be associated with a single set of credentials. If more than one set of credentials will be used, you should create a new API object instance each time you switch credentials.
const SendSafely = require('@sendsafely/sendsafely');
//Initialize the API var sendSafely = new SendSafely("https://app.sendsafely.com", "INSERT_API_KEY_HERE", " INSERT_API_SECRET_HERE "); //Verify that the API credentials are valid //We can choose if we want a synchronous call, what to do in case of an error //and what to do when we get a response sendSafely.verifyCredentials(function(email) { console.log("Connected to SendSafely as user " + email); });
Note that in the example above, the API credentials are verified using the verifyCredentials method, which returns the email address associated with the SendSafely user associated with the API key. Constructing the SendSafely object does not connect to SendSafely, so calling verifyCredentials is an optional step that can be used to verify you are using a valid API Key and API Secret.
Event Handling
The API relies heavily on events to pass data between the parent application and the API. To subscribe to events you can use the sendsafely.on function. The function takes two parameters.
- The name of the event you want to subscribe to.
- The function to be invoked once the event is fired.
The function returns an event ID that can be used to manage the event further on.
var eventId = sendSafely.on("sendsafely.some.event", function(data) { console.log("sendsafely.some.event just fired with data:"); console.log(data); });
You can also unbind the event when you are done using it. The unbind call accepts two parameters.
- The name of the event you want to unsubscribe from.
- [Optional] The specific event ID that you would like to unsubscribe from. If not specified all event IDs will be unsubscribed
sendSafely.unbind("sendsafely.some.event", eventId);
Creating a Package
Once the API instance has been initialized with credentials, you can use the instance to issue commands to SendSafely that create, edit, or delete packages as the user that created the API key. The example below shows how to create new empty package. Note that the createPackage method's callback function returns some metadata about the package that will be used later on in this tutorial. Most importantly, it returns a unique packageId that will be used to identify this package.
//Create a new empty package function finished(packageId, serverSecret, packageCode, keyCode) { console.log("Created new empty package with Package ID" + packageId); } sendSafely.createPackage(finished);
The callback function gives back some critical properties that are needed for subsequent API calls: the packageId, the packageCode and the serverSecret.
- The Package ID is the primary identifier used to reference the package for all subsequent API operations that manipulate or query this package.
- The Package Code is a unique token, which will be used in the link that is later sent out to the recipients.
- The Server Secret is a package specific token which is used as one part of the encryption key.
Adding Recipients
Once a package has been created, you will need to add one or more recipients. Each recipient for a given package must have a unique email address. Note that the callback function for the addRecipient method returns a Recipient object that includes properties with available metadata about the recipient. The metadata returned includes a unique RecipientID, a list of previous SMS phone numbers provided by the user for this recipient, a flag indicating whether this recipient requires approval, and a list of package approvers if approval is required.
//Add a new recipient to the package sendSafely.addRecipient(packageId, "user@example.com", keyCode, function (newRecipient) { console.log("Added new recipient (Id# " + newRecipient.recipientId + ")"); });
After a recipient has been added, you have the option of providing their mobile phone number in order to require SMS authentication for access to package. This step is optional, and must include both a phone number and Country Code to indicate the country in which the phone number.
//Add an SMS number for the new recipient //This time we are not passing in any callback functions. //Callbacks are optional for all methods and does not have to be used. sendSafely.addRecipientPhonenumber(packageId, newRecipient.recipientId, "212-555-1212", "US");
Adding Files
One of the main benefits of using the SendSafely Client API is that it alleviates the need to deal with the complex process of encrypting and uploading files to the SendSafely server. The SendSafely API automatically handles the task of generating an encryption key, encrypting the file with OpenPGP, segmenting large files for upload, and uploading to the server.
Because this step can take a comparatively larger amount of time than other API operations (which generally require a single request/response to the server) the will use a few extra events you might want to implement to monitor the progress of each file as it is being encrypted, signed and uploaded.
- sendsafely.files.attached: Raised when a unique file ID has been created for the given file. This event will fire once for every file being uploaded
- sendsafely.progress: Progress indicator that will be raised periodically throughout the upload.
//Progress event callback function myProgressCallback(data) { console.log("File with id #" + data.fileId + " has uploaded " data.percent + "%"); } //Attached event callback function myAttachCallback(data) { console.log("File with id #" + data.fileId + " and name: " + data.name + " has been attached"); }
sendSafely.on("sendsafely.files.attached", myAttachCallback);
sendSafely.on("sendsafely.progress", myProgressCallback);
//Now we are ready to open and attach the file
const fs = require('fs');
fs.readFile("test_file.txt", function(err, data) {
if (err) {
throw err
}
var file = {
size: data.length,
name:"test_file.txt",
data: data
};
sendSafely.encryptAndUploadFiles(newPackageId, newKeyCode, newServerSecret, fileArray, "js", function(packageId, fileId, fileSize, fileName) {
console.log("Upload Complete");
});
}
Finalizing or Deleting a Package
Once you have added at least one file and one recipient, the package can be finalized, indicating that its preparation is complete and there are no more files or recipients to be added. The FinalizePackage method is the last method that should be called, and it returns the full hyperlink that can be provided to recipients in order to access the package.
//Finalize the package so we can send the link to our recipient sendSafely.finalizePackage(packageId, packageCode, keyCode, function (url) { console.log("Package was finalized. The package can be downloaded from the following URL: " + url); });
Keep in mind that there is a limit of 5 incomplete packages at any time for each user. Incomplete package are packages that have at least one file or one recipient, but have not been finalized. If you wish to discard a package that has not been finalized, you can do so using the deleteTempPackage method.
//Delete the temp package if we are going to bail and not finalize sendSafely.deleteTempPackage(packageId); console.log("Temp package " + packageId + " was deleted.");
Downloading Files
The API can also be used to download files that someone sent to you. Our API offers a few methods making receiving data as easy as possible. Most of the time you will receive a SendSafely link from someone. The API offers a method of extracting a Package object from the link.
function callback(pkg) { console.log("Got the package"); console.log(pkg); } String myLink = "https://www.sendsafely.com/receive/?thread=AAAA-BBBB&packageCode=ABC#keyCode=123"; sendsafely.packageInformationFromLink(myLink, callback);
The API also offers a method to extract SendSafely links from a String of text. This is helpful if you want to list all links found in an email or a Zendesk Ticket. Use the following helper function to obtain a list of all SendSafely links found in the text:
var links = sendsafely.parseLinks(myEmail);
Once you have the Package object, you can download any file contained in the package. By default a save file event will be triggered when the file is done downloading. At that point it can be saved to the file system. You can override this behavior by specifying a custom config object. See the API Reference for more information.
sendsafely.on("save.file", function(data){ var fileId = data.fileId; // file is a blob that can now be saved to the file system. var file = file; }); sendsafely.packageInformationFromLink(myLink, function(pkg) { // Download all files found in the package pkg.files.forEach(function(file) { sendsafely.downloadFile(pkg.packageId, file.fileId, pkg.keyCode); }); });
Similar to when uploading files you can subscribe to a progress event to receive feedback on how the download of the file is going. To do so, simply subscribe to the following event:
sendsafely.on("download.progress", function(data){ console.log("File ID: " + data.fileId + " Percent: " + data.progress); });
Based on this article, you should now be able to integrate the SendSafely JavaScript API into your own application.