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==")
