go-macaroon / js-macaroon

Javascript implementation of macaroons
BSD 3-Clause "New" or "Revised" License
41 stars 22 forks source link

Use util.TextEncoder when window.TextEncoder is not present. #32

Closed squidsoup closed 6 years ago

squidsoup commented 6 years ago

Some js test environments such as Jest provide a window object, but not TextEncoder, which results in TextEncoder being undefined and never set to util.TextEncoder.

e.g.

TypeError: TextEncoder is not a constructor

    > 1 | import { Bakery, BakeryStorage } from "macaroon-bakery";
        | ^
      2 |
      3 | // Initialise Macaroon Bakery singleton
      4 | const visit = error => {

      at Object.<anonymous> (node_modules/macaroon/macaroon.js:19:21)
      at Object.<anonymous> (node_modules/macaroon-bakery/index.js:5:21)
      at Object.<anonymous> (src/bakery.js:1:1)

npm run check appears to fail, but not due to my change:

/Users/kit/src/canonical/js-macaroon/macaroon.js
  1119:1  error  Expected indentation of 6 spaces but found 8  indent
  1120:1  error  Expected indentation of 6 spaces but found 8  indent
hatched commented 6 years ago

Thanks for the PR @squidsoup

Because of the lint failure you never actually got to run the tests which fail:

~/code/js-macaroon/macaroon.js:20
if (window && window.TextEncoder) {
^

ReferenceError: window is not defined
    at ~/code/js-macaroon/macaroon.js:20:1
    at Object.<anonymous> (~/code/js-macaroon/macaroon.js:1293:4)

Your fix is appreciated and an improvement, but if you could apply the following diff then it should all work as intended.

diff --git a/macaroon.js b/macaroon.js
index 857bfb1..cdde714 100644
--- a/macaroon.js
+++ b/macaroon.js
@@ -17,7 +17,7 @@ const nacl = require('tweetnacl');
 const naclutil = require('tweetnacl-util');

 let TextEncoder, TextDecoder;
-if (window && window.TextEncoder) {
+if (typeof window !== 'undefined' && window && window.TextEncoder) {
   TextEncoder = window.TextEncoder;
   TextDecoder = window.TextDecoder;
 } else {
@@ -1116,8 +1116,8 @@ const newMacaroon = function({identifier, location, rootKey, version} = {}) {
     identifierBytes: identifierBytes,
     locationStr: maybeString(location, 'Macaroon location'),
     signatureBytes: bitsToBytes(keyedHash(
-        makeKey(bytesToBits(rootKeyBytes)),
-        bytesToBits(identifierBytes))),
+      makeKey(bytesToBits(rootKeyBytes)),
+      bytesToBits(identifierBytes))),
   });
 };
squidsoup commented 6 years ago

@hatched thanks Jeff, applied those changes as requested.