diff --git a/node-atob.js b/node-atob.js index d7305a3..9e2c2b1 100644 --- a/node-atob.js +++ b/node-atob.js @@ -1,6 +1,11 @@ "use strict"; +const b64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + function atob(str) { + for (const ch of str) + if (!b64Alphabet.includes(ch)) + throw new Error(`Invalid character '${ch}' in base64 String`); return Buffer.from(str, 'base64').toString('binary'); } diff --git a/test.js b/test.js index bd80a4e..b10bc54 100644 --- a/test.js +++ b/test.js @@ -4,6 +4,7 @@ var atob = require('.'); var encoded = "SGVsbG8sIFdvcmxkIQ==" var unencoded = "Hello, World!"; + var malformed = "SGVsbG8s{" /* , encoded = "SGVsbG8sIBZM" , unencoded = "Hello, 世界" @@ -14,5 +15,13 @@ return; } + try { + const decoded = atob(malformed) + console.log('[FAIL]', malformed, decoded); + return; + } catch (_) { + /* pass */ + } + console.log('[PASS] all tests pass'); }());