Putting TOTP into Google Spreadsheet using Google Apps Script

Gists

In this post, I would like to introduce a sample script for putting Time-based One-time Password (TOTP) value into Google Spreadsheet using Google Apps Script.

In this sample script, I used a Javascript library of https://github.com/hectorm/otpauth . In the current stage, Google Apps Script can run with V8 runtime. By this, it seems that this library can be used with Google Apps Script.

Sample script

function myFunction() {
  const secret = "ABCDEFGHIJKLMN23"; // Please set your secret here.
  const n = 3; // Code is created 5 times every 30 seconds.

  // Loading otpauth.umd.min.js (Ref: https://github.com/hectorm/otpauth)
  const cdnjs =
    "https://cdnjs.cloudflare.com/ajax/libs/otpauth/9.1.1/otpauth.umd.min.js";
  eval(UrlFetchApp.fetch(cdnjs).getContentText());

  const sheet = SpreadsheetApp.getActiveSheet();
  let c = n;
  while (c > 0) {
    const now = new Date();
    const code = new OTPAuth.TOTP({
      secret,
      algorithm: "SHA1",
      digits: 6,
      period: 30,
    }).generate();
    const [start, end] = [now, new Date(now.getTime() + 30000)].map((e) =>
      Utilities.formatDate(e, Session.getScriptTimeZone(), "HH:mm:ss")
    );
    sheet.appendRow([code, `Limit: ${start} - ${end}`]);
    SpreadsheetApp.flush();
    c--;
    if (c > 0) Utilities.sleep(30000);
  }
  sheet.appendRow(["Done."]);
}

Testing

When this script is run, the situation of the above demonstration is obtained.

And, as a test, when I use the code retrieved by this sample script with 2FA of GitHub, I confirmed that the code could be used for correctly logging in to GitHub.

IMPORTANT

In this sample, the script of https://cdnjs.cloudflare.com/ajax/libs/otpauth/9.1.1/otpauth.umd.min.js is loaded with eval. If you cannot use this, you can also use this script by copying and pasting the script of https://cdnjs.cloudflare.com/ajax/libs/otpauth/9.1.1/otpauth.umd.min.js to the script editor. By this, you can remove eval(UrlFetchApp.fetch(cdnjs).getContentText());. When the script of otpauth.umd.min.js is put in the script editor, the process cost can be reduced rather than that using eval(UrlFetchApp.fetch(cdnjs).getContentText());.

 Share!