From e8c9f6873a2291958bad19329fb9b4a037f52c21 Mon Sep 17 00:00:00 2001 From: Marvin Borner Date: Sat, 26 Jan 2019 00:13:48 +0100 Subject: Travelling through the madness of asynchronousity --- public/scripts/2_encryption.js | 99 +++++++++++++++++++++++++++--------------- public/scripts/chat.js | 51 +++++++++++++--------- 2 files changed, 94 insertions(+), 56 deletions(-) (limited to 'public') diff --git a/public/scripts/2_encryption.js b/public/scripts/2_encryption.js index c094c2c..17bce3d 100644 --- a/public/scripts/2_encryption.js +++ b/public/scripts/2_encryption.js @@ -3,19 +3,44 @@ const openpgp = require('openpgp'); openpgp.initWorker({path: 'openpgp.worker.js'}); /** - * Generated localstorage database and tables - * @returns {boolean} + * Generates database and tables + * @returns Boolean */ function setupDatabase() { - sql('CREATE localStorage DATABASE IF NOT EXISTS texx_ls'); - sql('ATTACH localStorage DATABASE texx_ls AS db'); - sql('SET AUTOCOMMIT ON'); - sql('CREATE TABLE IF NOT EXISTS db.own_keys (key_type STRING, key_data STRING)'); - sql('CREATE TABLE IF NOT EXISTS db.peer_keys (peer_id STRING, key_data STRING)'); - sql('CREATE TABLE IF NOT EXISTS db.messages (id INT AUTO_INCREMENT, message STRING)'); - return true; + return sql('CREATE INDEXEDDB DATABASE IF NOT EXISTS texx; \ + ATTACH INDEXEDDB DATABASE texx; \ + USE texx; \ + CREATE TABLE IF NOT EXISTS own_keys (key_type STRING, key_data STRING); \ + CREATE TABLE IF NOT EXISTS peer_keys (peer_id STRING, key_data STRING); \ + CREATE TABLE IF NOT EXISTS messages (id INT AUTO_INCREMENT, message STRING);', () => { + localStorage.setItem('database', 'success'); + return true; + }) } +/** + * Sets up connection between memory storage and indexeddb + */ +function setupDatabaseConnection() { + sql.promise('CREATE INDEXEDDB DATABASE IF NOT EXISTS texx; ATTACH INDEXEDDB DATABASE texx; USE texx;') +} + +window.test = (() => { + sql('CREATE INDEXEDDB DATABASE IF NOT EXISTS geo;\ + ATTACH INDEXEDDB DATABASE geo; \ + USE geo; \ + CREATE TABLE IF NOT EXISTS cities (city string, population number); \ + INSERT INTO cities Values ("' + (Math.random() * 100) + '","' + (Math.random() * 100) + '")', function () { + + // Select data from IndexedDB + sql.promise('SELECT * FROM cities') + .then(function (res) { + console.log(res); + }); + }); +}); + + /** * Generates and stores encrypted private key, public key and a revocation certificate * @param peerId @@ -29,39 +54,37 @@ async function generateKeys(peerId, passphrase) { passphrase: passphrase }; - await openpgp.generateKey(options).then((key) => { - sql(`INSERT INTO db.own_keys VALUES ("private_key", "${key.privateKeyArmored}")`); - sql(`INSERT INTO db.own_keys VALUES ("public_key", "${key.publicKeyArmored}")`); - sql(`INSERT INTO db.own_keys VALUES ("revocation_certificate", "${key.revocationCertificate}")`); - console.log('[LOG] Successfully generated and stored keys!'); + await openpgp.generateKey(options).then(async (key) => { + await sql.promise([`INSERT INTO own_keys VALUES ("private_key", "${key.privateKeyArmored}");`, + `INSERT INTO own_keys VALUES ("public_key", "${key.publicKeyArmored}");`, + `INSERT INTO own_keys VALUES ("revocation_certificate", "${key.revocationCertificate}");`]).then(() => + console.log('[LOG] Successfully generated and stored keys!') + ); }); } /** * Gets the peers private key - * @returns {string} + * @returns {Promise} */ -function getPrivateKey() { - const privateKey = sql('SELECT key_data FROM db.own_keys WHERE key_type = "private_key" LIMIT 1'); - return privateKey.length > 0 ? privateKey[0]['key_data'] : ''; +async function getPrivateKey() { + return await sql.promise('SELECT key_data FROM own_keys WHERE key_type = "private_key" LIMIT 1').then(res => res.length > 0 ? res[0]['key_data'] : ''); } /** * Gets the peers public key - * @returns {string} + * @returns {Promise} */ -function getPublicKey() { - const publicKey = sql('SELECT key_data FROM db.own_keys WHERE key_type = "public_key" LIMIT 1'); - return publicKey.length > 0 ? publicKey[0]['key_data'] : ''; +async function getPublicKey() { + return await sql.promise('SELECT key_data FROM own_keys WHERE key_type = "public_key" LIMIT 1').then(res => res.length > 0 ? res[0]['key_data'] : ''); } /** * Gets the peers revocation certificate - * @returns {string} + * @returns {Promise} */ -function getRevocationCertificate() { - const revocationCertificate = sql('SELECT key_data FROM db.own_keys WHERE key_type = "revocation_certificate" LIMIT 1'); - return revocationCertificate.length > 0 ? revocationCertificate[0]['key_data'] : ''; +async function getRevocationCertificate() { + return await sql.promise('SELECT key_data FROM own_keys WHERE key_type = "revocation_certificate" LIMIT 1').then(res => res.length > 0 ? res[0]['key_data'] : ''); } /** @@ -113,10 +136,10 @@ async function decrypt(data, publicKey, privateKey, passphrase) { * Checks whether the peer has keys * @returns {boolean} */ -function isEncrypted() { - const hasPrivateKey = getPrivateKey() !== ''; - const hasPublicKey = getPublicKey() !== ''; - const hasRevocationCertificate = getRevocationCertificate() !== ''; +async function isEncrypted() { + const hasPrivateKey = await getPrivateKey().then(res => res !== ''); + const hasPublicKey = await getPublicKey().then(res => res !== ''); + const hasRevocationCertificate = await getRevocationCertificate().then(res => res !== ''); return (hasPrivateKey && hasPublicKey && hasRevocationCertificate); } @@ -125,20 +148,23 @@ function isEncrypted() { * @param peerId * @param key */ -function storePeerPublicKey(peerId, key) { +async function storePeerPublicKey(peerId, key) { console.log(peerId); console.log(key); - sql(`INSERT INTO db.peer_keys VALUES ("${peerId}", "${key}")`); - console.log('[LOG] Stored public key of ' + peerId); + await sql.promise(`INSERT INTO peer_keys VALUES ("${peerId}", "${key}")`).then(() => + console.log('[LOG] Stored public key of ' + peerId) + ); } /** * Gets the public key of a peer * @param peerId + * @returns {Promise} */ -function getPeerPublicKey(peerId) { - const publicKey = sql(`SELECT key_data FROM db.peer_keys WHERE peer_id = "${peerId}" LIMIT 1`); - return publicKey.length > 0 ? publicKey[0]['key_data'] : ''; +async function getPeerPublicKey(peerId) { + return await sql.promise(`SELECT key_data FROM peer_keys WHERE peer_id = "${peerId}" LIMIT 1`).then(res => + res.length > 0 ? res[0]['key_data'] : '' + ); } /** @@ -156,6 +182,7 @@ function testEncryption() { } exports.setup = setupDatabase; +exports.setupConn = setupDatabaseConnection; exports.generate = generateKeys; exports.getPrivate = getPrivateKey; exports.getPublic = getPublicKey; diff --git a/public/scripts/chat.js b/public/scripts/chat.js index 6c5271e..e81bd44 100644 --- a/public/scripts/chat.js +++ b/public/scripts/chat.js @@ -7,13 +7,16 @@ let connectedPeer; const peerId = nanoid(); // setup encryption -if (encryption.setup() && encryption.check()) { - // TODO: Ask for passphrase - chat(); -} else { - console.log('[LOG] No existing keys found! Generating...'); - encryption.generate(peerId, 'supersecure').then(() => chat()); -} +(async () => { + if (localStorage.getItem('database') === 'success' && encryption.setupConn() && await encryption.check()) { + // TODO: Ask for passphrase + chat(); + } else { + console.log('[LOG] No existing keys found! Generating...'); + encryption.setup(); + (async () => await encryption.generate(peerId, 'supersecure').then(() => chat()))() + } +})(); function chat() { const peer = new Peer(peerId, {host: '127.0.0.1', port: 4242, path: '/', debug: 0}); @@ -24,8 +27,8 @@ function chat() { peer.on('connection', conn => { connectedPeer = conn; console.log('[LOG] Connected with', connectedPeer.peer); - connectedPeer.on('open', () => transferKey(encryption.getPublic())); - connectedPeer.on('data', message => receivedMessage(message)); + connectedPeer.on('open', async () => await encryption.getPublic().then(res => transferKey(res))); + connectedPeer.on('data', async message => await receivedMessage(message)); }); /** @@ -38,19 +41,22 @@ function chat() { console.log('[LOG] Your connection ID is', connectionId); connectedPeer = peer.connect(id, {label: connectionId, reliable: true}); console.log('[LOG] Connected with', connectedPeer.peer); - connectedPeer.on('open', () => transferKey(encryption.getPublic())); - connectedPeer.on('data', message => receivedMessage(message)) + connectedPeer.on('open', async () => await encryption.getPublic().then(res => transferKey(res))); + connectedPeer.on('data', async message => await receivedMessage(message)) } /** * Sends a message to the peer with which you're currently connected * @param message + * @returns {Promise} */ - function sendMessage(message) { + async function sendMessage(message) { console.log(`[LOG] Sending message ${message} to ${connectedPeer.peer}`); - encryption.encrypt(message, encryption.get(connectedPeer.peer)).then(encrypted => { - connectedPeer.send({type: 'text', data: encrypted}); - receivedMessage(message, true); + await encryption.get(connectedPeer.peer).then(async peerKey => { + await encryption.encrypt(message, peerKey).then(async encrypted => { + connectedPeer.send({type: 'text', data: encrypted}); + await receivedMessage(message, true); + }) }) } @@ -68,15 +74,20 @@ function chat() { * @param message * @param self */ - function receivedMessage(message, self = false) { + async function receivedMessage(message, self = false) { if (self) { $('#messages').append(`${message}
`); } else { if (message.type === 'text') { - encryption.decrypt(message.data, encryption.get(connectedPeer.peer), encryption.getPrivate(), 'supersecure') - .then(plaintext => $('#messages').append(`${plaintext}
`)); + // TODO: Cleanup async method calls + await encryption.get(connectedPeer.peer).then(async peerKey => { + await encryption.getPrivate().then(async privateKey => { + await encryption.decrypt(message.data, peerKey, privateKey, 'supersecure') + .then(plaintext => $('#messages').append(`${plaintext}
`)); + }) + }) } else if (message.type === 'key') { - encryption.store(connectedPeer.peer, message.data) + await encryption.store(connectedPeer.peer, message.data) } } } @@ -86,7 +97,7 @@ function chat() { */ $(document).ready(() => { $('#add_peer_id').on('click', () => connect($('#peer_id').val())); - $('#send_message').on('click', () => sendMessage($('#message').val())); + $('#send_message').on('click', async () => await sendMessage($('#message').val())); $('[toggle-contact-modal]').on('click', () => $('#add_contact_modal').toggleClass('is-active')) }); -- cgit v1.2.3