Files

64 lines
2.2 KiB
Diff

diff --git a/index.js b/index.js
index 7a0e9c2a123bc9d26c20bb3de4a3c4e49b24ee40..e750c4f51b436fae4cd82d58b43666442b95a3a3 100644
--- a/index.js
+++ b/index.js
@@ -377,6 +377,7 @@ Buffer.isEncoding = function isEncoding (encoding) {
case 'latin1':
case 'binary':
case 'base64':
+ case 'base64url':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
@@ -466,6 +467,7 @@ function byteLength (string, encoding) {
case 'hex':
return len >>> 1
case 'base64':
+ case 'base64url':
return base64ToBytes(string).length
default:
if (loweredCase) {
@@ -534,6 +536,9 @@ function slowToString (encoding, start, end) {
case 'base64':
return base64Slice(this, start, end)
+ case 'base64url':
+ return base64urlSlice(this, start, end)
+
case 'ucs2':
case 'ucs-2':
case 'utf16le':
@@ -917,6 +922,7 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
return asciiWrite(this, string, offset, length)
case 'base64':
+ case 'base64url':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
@@ -949,6 +955,14 @@ function base64Slice (buf, start, end) {
}
}
+function base64urlSlice (buf, start, end) {
+ // base64url is base64 with a URL-safe alphabet and no padding
+ return base64Slice(buf, start, end)
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_')
+ .replace(/=+$/, '')
+}
+
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
const res = []
@@ -1942,6 +1956,9 @@ function base64clean (str) {
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
+ // Translate the URL-safe base64url alphabet to standard base64 so that
+ // 'base64url'-encoded input decodes correctly via base64-js
+ str = str.replace(/-/g, '+').replace(/_/g, '/')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not