in

The best way to Share Google Docs Securely with a Google Apps Script

blank - The best way to Share Google Docs Securely with a Google Apps Script


oc1ae32jh - The best way to Share Google Docs Securely with a Google Apps Script

Add Further Knowledge Protections to G Suite with the Virtru SDK

I’m not a developer. I do know a bit JavaScript and Python — sufficient to write down a few fundamental scripts to assist with a few of my extra mundane duties — however I definitely don’t have the abilities or know-how to write down precise software program. What I do know, nonetheless, are my prospects and the challenges they face in preserving their information safe. So after we launched the Virtru SDK, touting its ease of use, I used to be skeptical. How onerous is that this going to be for my prospects to combine into their current workflows? Might somebody with my restricted coding abilities construct one thing with this? Let’s discover out!
TL; DR: Sure. It truly is very easy so as to add the Virtru SDK to your challenge, as I’ll exhibit via the development of a “Shield & Share” Google Docs add-on. See the finished challenge right here.

To discover a challenge that might each add worth to my present workflows and exhibit the capabilities of the Virtru SDK, I requested myself three questions:

What are my commonest workflows?

Effectively, we’re a G Suite store, so let’s begin there. I spend rather a lot of time in Google Docs. Whether or not taking notes, writing stories, growing customer-facing documentation, or drafting this very weblog publish, it’s a uncommon day that I don’t work in no less than one Google Doc. And since these paperwork could be internal-only or customer-facing, I’m at all times making an attempt to determine how greatest to share them.

Might these workflows use further layers of information safety?

Google has some nice protections and controls for sharing Docs content material with different G Suite customers, however the expertise sharing outdoors the Google ecosystem has at all times been missing. If you wish to share a Doc with a non-Google person, you’re compelled to make your information semi-public on the web with no assure that it’ll solely be accessed by approved events. Even for my least-sensitive paperwork, I’m not thrilled with this requirement; for my most delicate content material, it’s a showstopper.

What’s the bottom barrier to entry?

After I suppose “add options to G Suite”, I usually suppose “Chrome Extension”. However not too long ago I’ve been experimenting with Google Apps Script, and it’s clearly the extra compelling answer for this use case. The code runs immediately inside G Suite, so I gained’t should construct and package deal an extension. It’s JavaScript & HTML-based, so it is going to help Virtru’s browser JS SDK. And it’s designed to do precisely what I finally need to do: construct add-ons to increase Google Sheets, Docs, & Slides.

To construct a Google Docs add-on that may permit me to generate a safe, encrypted copy of my Google Docs content material and share it privately with approved customers. To that finish, I’ll want so as to add the next capabilities to the Docs UI:

– Seize Google Doc content material in a PDF.

– Encrypt that PDF with coverage controls set by the person reminiscent of doc watermarking, expiration date, and disable re-sharing.

– Obtain the encrypted PDF, OR

– Ship the encrypted PDF as an electronic mail attachment.

The primary, third, and fourth capabilities above are all easy and simply achieved with the instruments accessible in Google Apps Script. The one new performance I would like so as to add is to encrypt the doc and apply my entry controls.

When In Doubt, Copy & Paste

With zero expertise writing a Docs add-on, I’ve determined to easily copy this pattern translation challenge from Google’s personal documentation, rip out the elements I didn’t want, then add my very own code.
A fundamental add-on has two elements: server-side code operating inside the Google Apps Script atmosphere — ‘Code.gs’ — and client-side code operating immediately on the web page — ‘virtruSidebar.html’. I need to encrypt client-side, so I can copy some pattern code from the Virtru Developer Hub’s browser JS quick-start into my client-side HTML file to import the Virtru SDK and styling:
<head>
    <hyperlink href="https://sdk.virtru.com/js/newest/auth-widget/index.css" rel="stylesheet"/>
    <script src="https://sdk.virtru.com/js/newest/auth-widget/index.js"></script>
    <script src="https://sdk.virtru.com/js/newest/virtru-sdk.min.js"></script>
</head>

Above: virtruSidebar.html – Including Virtru SDK & styling to client-side HTML.

Subsequent, I would like so as to add the factor that may truly carry out the encryption step — the Virtru ‘shopper’. Once more, the browser JS quick-start has some useful code I can copy to generate the shopper:
<physique>
  <div id="virtru-auth-widget-mount"></div>
  <script sort="textual content/javascript">
    async perform afterAuth(electronic mail) {
      // Run all shopper code from right here. 
      // This can solely be known as when the person is efficiently authenticated.
      const shopper = new Virtru.Shopper({electronic mail});
      const yourString = immediate('Sort a sting to encrypt: ', 'Whats up, world!');
      const encryptParams = new Virtru.EncryptParamsBuilder()
        .withStringSource(yourString)
        .withDisplayFilename('whats up.txt')
        .construct();
      const ct = await shopper.encrypt(encryptParams);
      await ct.toFile('whats up.html');
    }
    // Arrange the auth widget.
    Virtru.AuthWidget('virtru-auth-widget-mount', {afterAuth});
  </script>
</physique>

Above: virtruSidebar.html – Loading default Virtru shopper.

It is a good begin, however as-is, this shopper is configured to simply accept a easy string enter and output an encrypted .txt file; I have to take a PDF as enter and output an encrypted PDF earlier than it will truly be helpful.

Producing a PDF

As famous above, most of what this add-on will do could be achieved with the native instruments accessible in Google Apps Script, together with the era of a PDF from Google Docs content material. First, I’ll add some server-side code to generate a blob from the present doc and format as a base-64 string for simple transport to the shopper:

perform createPDF() {
  var docBlob = DocumentApp.getActiveDocument().getBlob();
  docBlob.setName(doc.getName() + '.pdf');
  var blobB64 = Utilities.base64Encode(docBlob.getBytes());
  return blobB64;
}

Above: Code.gs – Creating PDF blob from Google Doc content material.

After which a client-side perform to name the above server-side perform and return the doc information to the shopper:


   /*      
    * Runs server-side perform to return the contents
    * of the doc in base64 format.
    *
    * @return {string} Base 64'd doc content material.
    */    
         perform genPDF() {
           return new Promise(perform(resolve, reject) {
             google.script.run
               .withSuccessHandler(perform(blobB64) {
                 resolve(blobB64);
               })
               .createPDF();
           });
         }

Above: virtruSidebar.html – Calling the server-side perform to generate pdf blob & transport to shopper.

Customizing the Fast Begin

With a purpose to encrypt a file relatively than a easy textual content string, I’ll make two changes to the Virtru shopper:

Change the info supply for encryption from string to array buffer. With an array buffer enter, the shopper can settle for any file sort as long as it has been appropriately transformed beforehand.Change the output sort to make sure the ultimate encrypted file will render as and decrypt to PDF.virtruSidebar.html: Updating the shopper to simply accept arrayBuffer and output pdf.tdf3.html.
    async perform afterAuth(electronic mail) {
      // Run all shopper code from right here. 
      // This can solely be known as when the person is efficiently authenticated.
      const shopper = new Virtru.Shopper({electronic mail});
      const yourString = immediate('Sort a sting to encrypt: ', 'Whats up, world!');
      const encryptParams = new Virtru.EncryptParamsBuilder()
        .withArrayBufferSource(arrayBuffer)    // Change enter to simply accept arrayBuffer
        .withDisplayFilename('whats up.pdf')      // Change show filename to mirror PDF
        .construct();
      const ct = await shopper.encrypt(encryptParams);
      await ct.toFile('whats up.pdf.tdf3.html');  // Change output file extension to pdf.tdf3.html
    }
    // Arrange the auth widget.
    Virtru.AuthWidget('virtru-auth-widget-mount', {afterAuth});

Above: virtruSidebar.html – Updating the shopper to simply accept arrayBuffer and output pdf.tdf3.html.

At this level, the add-on can generate an encrypted copy of the Google Doc. Nice! Nevertheless, it lacks any entry controls or sharing choices. By default, the doc proprietor is the one approved person. Let’s change that.

Including Entry Controls

Every information object protected by Virtru encryption is related to a coverage that dictates the approved recipients and entry controls reminiscent of expiration date & watermarking. Based mostly on the info proprietor’s inputs, I can assemble a coverage object to go to the encryption shopper. Within the instance beneath, person enter is captured by a collection of checkbox parts, however you need to use no matter mechanism you want:
   /*
    * Builds coverage in response to person inputs. 
    *
    * @param {Array}   authUsers  The checklist of approved customers for this piece of content material.
    * @return {Coverage}            The coverage for this piece of content material.
    */    
         perform buildPolicy() {
           var coverage = new Virtru.PolicyBuilder();
   
           if ($('#watermark-toggle').is(":checked")) {
             coverage.enableWatermarking();
           } 
           if ($('#disable-reshare-toggle').is(":checked")) {
             coverage.disableReshare();    
           } 
           if ($('#expiration-toggle').is(":checked")) {
             if ($('#one-hour-expire').is(":checked")) {
               var expTime = (60*60);    // Expiration time is about in "seconds from now"
               console.log(expTime);
             }
             if ($('#one-day-expire').is(":checked")) {
               var expTime = (60*60*24);
               console.log(expTime);
             }
             if ($('#one-week-expire').is(":checked")) {
               var expTime = (60*60*24*7);
               console.log(expTime);
             }
             if ($('#one-month-expire').is(":checked")) {
               var expTime = (60*60*24*7*4);
               console.log(expTime);
             }
             coverage.enableExpirationDeadlineFromNow([expTime]);
           } 
           return coverage.construct();
         }

Above: virtruSidebar.html – Creating an entry management coverage primarily based on person enter checkboxes.

The coverage is then handed to the encryption shopper. Licensed customers could be included within the coverage object itself, or added as an extra encryption parameter {array} as proven right here:

 const encryptParams = new Virtru.EncryptParamsBuilder()
  .withArrayBufferSource(arrayBuffer)
  .withDisplayFilename(`${docTitle}.pdf`)
  .withPolicy(coverage)
  .withUsersWithAccess(authorizedUsers)
  .construct();

Above: virtruSidebar.html – Including the coverage object and approved customers to the encrypt shopper.

Sending an Electronic mail

If I need to electronic mail the encrypted file to the approved customers relatively than obtain it, I would like to alter the code a bit. As a substitute of encrypting on to a file, I’ll encrypt to a string. That string consists of the encrypted file ciphertext and the HTML information that permits a person to open it within the browser:

           const shopper = new Virtru.Shopper({electronic mail});
           const encryptParams = new Virtru.EncryptParamsBuilder()
             .withArrayBufferSource(arrayBuffer)
             .withDisplayFilename(`${docTitle}.pdf`)
             .withPolicy(coverage)
             .withUsersWithAccess(authorizedUsers)
             .construct();
           const ct = await shopper.encrypt(encryptParams);
           var ctString = await ct.toString();  // Encrypt to string relatively than to file
          
           // Run server-side perform to generate an electronic mail
           // to the checklist of approved customers and embody
           // the HTML generated above as an attachment. 
           var userMessage = $('#email-body').val().exchange(/n/g, '<br/>');
                      // Take person enter from a discipline within the sidebar and protect line breaks
           google.script.run.sendEmail(ctString, authorizedUsers, userMessage);

Above: virtruSidebar.html – Updating the shopper to ship encrypted content material server-side for electronic mail era.

This string can then be handed to a server-side perform to create an electronic mail with the encrypted file connected:


perform sendEmail(cipherText, recipients, userMessage) {

  // Get electronic mail deal with of file proprietor and assign attachment title.
  var fileOwner = Session.getActiveUser().getEmail();
  var fileName = DocumentApp.getActiveDocument().getName() + ".pdf.tdf3.html";
  
  // Present a fundamental electronic mail physique for recipients who don't help HTML.
  var emailBody = fileOwner + " has shared the encrypted file " + fileName + 
      " with you.rnrnIt's connected beneath; please obtain to open in" + 
      " Virtru's Safe Reader.";
  
  // Assign values to variables in emailHTML.html template.
  var htmlContent = HtmlService.createTemplateFromFile('emailHTML');
  htmlContent.fileOwner = fileOwner;
  htmlContent.fileName = fileName;
  htmlContent.userMessage = userMessage;
  
  // Create topic line primarily based on filename and proprietor electronic mail deal with. 
  var topic = fileOwner + ' has shared a safe file: "' + fileName + '"';
  
  // Convert ciphertext string to HTML blob.
  var blob = Utilities.newBlob(cipherText, 'textual content/html', fileName);
  
  // Ship the e-mail with the tdf.html blob as attachment.
  MailApp.sendEmail(recipients, topic, emailBody, {
    title: fileOwner,
    attachments: [blob],
    htmlBody: htmlContent.consider().getContent()
  });
}

Above: Code.gs – Server-side perform to generate and ship an electronic mail with encrypted attachment.

With all of the elements working as wanted, the ultimate step is to make this into one thing a human can truly use. I added some toggles, buttons, textual content enter fields, and a bit jQuery to permit customers to carry out the next actions:

Select “Encrypt & Obtain” or “Encrypt & Electronic mail”.Add approved customers.Add entry controls.Embody a customized message to electronic mail recipients.

This truly accounted for almost all of code that I wrote for this challenge. The protection-specific items — encrypting the file and including entry controls — account for a really small portion of the add-on. And of that portion, I copied and pasted most of it!

Encrypt & Obtain:

FcDZ4jtADaav7S2fw12rGNVDuP73 uz232o3 - The best way to Share Google Docs Securely with a Google Apps Script

Above: Encrypting, downloading, and previewing the doc.

Encrypt & Electronic mail:

FcDZ4jtADaav7S2fw12rGNVDuP73 0x17g32st - The best way to Share Google Docs Securely with a Google Apps Script

Above: Encrypting, emailing, and accessing the doc.

This ended up being simpler to implement than I assumed it could be. In reality, the steepest studying curve for me was determining the place Google Apps Script and vanilla JavaScript differ and the way they greatest work together. Including encryption to the add-on was virtually an afterthought. So whereas this challenge will not be immediately relevant to you or your group, it ought to illustrate how shortly you may combine information safety into your individual workflows.

With this underneath my belt, I believe I’ll attempt to develop some further capabilities or new add-ons to see how else I can leverage Google Apps Script in my day-to-day. Please let me know within the feedback if in case you have any concepts for subsequent initiatives or further options!

I’m a Options Engineer at Virtru, the place I work with our prospects to establish areas of their environments the place further information protections are wanted, and develop options utilizing Virtru’s Knowledge Safety Platform & SDKs to satisfy these wants. Our developer platform is constructed on our SaaS Key and Coverage Infrastructure to help information safety utilizing the open normal TDF3, audit, and management.



Source link

What do you think?

Written by Zeeshan

Leave a Reply

Your email address will not be published. Required fields are marked *

blank - Peak District Animation - #DoThisPeakDistrict (track model)

Peak District Animation – #DoThisPeakDistrict (track model)

blank - Pokemon Sword and Protect rolls out prolonged overview trailer

Pokemon Sword and Protect rolls out prolonged overview trailer