Skip to content

Commit 903ef45

Browse files
committed
Use atob() and btoa() instead of external package
1 parent 7340315 commit 903ef45

File tree

3 files changed

+33
-15
lines changed

3 files changed

+33
-15
lines changed

lib/util.js

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
const base64 = require("@hexagon/base64");
2-
31
const ApiError = require("./error");
42

53
/**
@@ -101,14 +99,45 @@ async function createHMACSHA256(secret, data) {
10199

102100
const key = await crypto.subtle.importKey(
103101
"raw",
104-
base64.toArrayBuffer(secret),
102+
base64ToBytes(secret),
105103
{ name: "HMAC", hash: "SHA-256" },
106104
false,
107105
["sign"]
108106
);
109107

110108
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
111-
return base64.fromArrayBuffer(signature);
109+
return bytesToBase64(signature);
110+
}
111+
112+
/**
113+
* Convert a base64 encoded string into bytes.
114+
*
115+
* @param {string} the base64 encoded string
116+
* @return {Uint8Array}
117+
*
118+
* Two functions for encoding/decoding base64 strings using web standards. Not
119+
* intended to be used to encode/decode arbitrary string data.
120+
* See: https://developer.mozilla.org/en-US/docs/Glossary/Base64#javascript_support
121+
* See: https://stackoverflow.com/a/31621532
122+
*
123+
* Performance might take a hit because of the conversion to string and then to binary,
124+
* if this is the case we might want to look at an alternative solution.
125+
* See: https://jsben.ch/wnaZC
126+
*/
127+
function base64ToBytes(base64) {
128+
return Uint8Array.from(atob(base64), (m) => m.codePointAt(0));
129+
}
130+
131+
/**
132+
* Convert a base64 encoded string into bytes.
133+
*
134+
* See {@link base64ToBytes} for caveats.
135+
*
136+
* @param {Uint8Array | ArrayBuffer} the base64 encoded string
137+
* @return {string}
138+
*/
139+
function bytesToBase64(bytes) {
140+
return btoa(String.fromCharCode.apply(null, new Uint8Array(bytes)));
112141
}
113142

114143
/**

package-lock.json

Lines changed: 0 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,5 @@
4545
"publint": "^0.2.7",
4646
"ts-jest": "^29.1.0",
4747
"typescript": "^5.0.2"
48-
},
49-
"dependencies": {
50-
"@hexagon/base64": "^1.1.28"
5148
}
5249
}

0 commit comments

Comments
 (0)