From 51506925bc263df214d9ffc90cd1fc8bae00e024 Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Fri, 24 Jul 2020 18:27:15 -0600 Subject: [PATCH] Move token stuff to single .js --- public/auth.js | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 public/auth.js diff --git a/public/auth.js b/public/auth.js new file mode 100644 index 0000000..7ed13d9 --- /dev/null +++ b/public/auth.js @@ -0,0 +1,62 @@ +class NewAuthToken { + constructor(key) { + if (!key) { + throw "invalid key" + } + this.key = key.repeat(32).substr(0, 32) + } + + decode(b64, callback) { + var ciphertext = this.base64_decode(b64) + + var iv = ciphertext.substr(0, 12) + var encrypted = ciphertext.substr(iv.length, ciphertext.length-iv.length) + + this.get_crypto_key() + .then(function(crypto_key) { + NewAuthToken.decrypt(crypto_key, iv, encrypted, callback) + }) + } + + base64_decode(b64) { + return atob(b64) + } + + static to_buffer(s) { + var bytes = new Uint8Array(s.length) + for (var i = 0; i < s.length; i++) { + bytes[i] = s.charCodeAt(i) + } + return bytes.buffer + } + + static decrypt(crypto_key, iv, encrypted, callback) { + window.crypto.subtle.decrypt( + {name: "AES-GCM", iv: NewAuthToken.to_buffer(iv)}, + crypto_key, + NewAuthToken.to_buffer(encrypted), + ) + .then(function(decrypted) { + callback(String.fromCharCode.apply(null, new Uint8Array(decrypted))) + }) + } + + get_crypto_key() { + return crypto.subtle.importKey( + "raw", + NewAuthToken.to_buffer(this.key), + "AES-GCM", + false, + ["decrypt"] + ) + } + + set_token(encoded_token) { + this.decode(encoded_token, function (token) { + console.log("Set-Cookie DnDex-Auth="+token) + document.cookie = "DnDex-Auth=" + token + ";path=/" + }) + } +} + +authtoken = new NewAuthToken("123").set_token("SOY05yF/9iv3YG71sKkQPVaEwO53PCX8qZhDHS9JUohBgVl5Qr9/GTKK/TJ6OozhHN7QBIGmHNzQxTRRSLs4Lw==")