add createKey and createKeySVG methods, support base32 key encoding
[squeep-totp] / test / totp.js
index 8c08bbf58a2f0357e8a93a0f7bccae1193dc8349..0d5a808d31966e9f676e56565c1facadbdc9c393 100644 (file)
@@ -2,7 +2,7 @@
 'use strict';
 
 const assert = require('assert');
-const sinon = require('sinon');
+const sinon = require('sinon'); // eslint-disable-line node/no-unpublished-require
 const TOTP = require('../lib/totp');
 
 describe('TOTP', function () {
@@ -102,7 +102,7 @@ describe('TOTP', function () {
       '0': '45301026', // oathtool --totp -N 'Sept 29 2023 02:58:00' --digits=8 3132333435363738393031323334353637383930
       '1': '16636878',
       '2': '37492012',
-    }
+    };
     beforeEach(function () {
       const when = new Date('2023-09-29T09:58:00.000Z');
       sinon.stub(Date, 'now').returns(when.getTime());
@@ -136,4 +136,34 @@ describe('TOTP', function () {
     });
   }); // validate
 
+  describe('createKey', function () {
+    for (const [algorithm, keySize] of Object.entries(TOTP._algorithmKeyLengths)) {
+      it(`creates a ${algorithm} key`, async function () {
+        options.algorithm = algorithm;
+        options.key = algorithmKeys[algorithm]; // eslint-disable-line security/detect-object-injection
+        const expected = keySize * 2; // hex encoding
+        const key = await TOTP.createKey(algorithm);
+        assert.strictEqual(key.length, expected);
+      });
+    }
+  }); // createKey
+
+  describe('createKeySVG', function () {
+    let options, key, keyEncoding;
+    beforeEach(function () {
+      options = {
+        issuer: 'Squeep',
+        accountname: 'test@example.com',
+      };
+      key = algorithmKeys['sha1'];
+      keyEncoding = 'buffer';
+    });
+    it('creates totp type qrcoded uri', function () {
+      const { secret, svg, uri } = TOTP.createKeySVG(options, key, keyEncoding);
+      assert(svg);
+      assert(uri.includes('totp'));
+      assert.strictEqual(secret, 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
+    });
+  }); // createKeySVG
+
 }); // TOTP
\ No newline at end of file