diff --git a/services/gunDB/Mediator/index.js b/services/gunDB/Mediator/index.js index 9464b6a5..9f6568a5 100644 --- a/services/gunDB/Mediator/index.js +++ b/services/gunDB/Mediator/index.js @@ -12,7 +12,6 @@ Gun.log = () => {} require('gun/lib/open') // @ts-ignore require('gun/lib/load') -const debounce = require('lodash/debounce') //@ts-ignore const { encryptedEmit, encryptedOn } = require('../../../utils/ECC/socket') const Key = require('../contact-api/key') @@ -215,14 +214,9 @@ mySEA.secret = async (recipientOrSenderEpub, recipientOrSenderSEA) => { return sec } -const auth = require('../../auth/auth') - const { Constants } = require('shock-common') -const { Action, Event } = Constants const API = require('../contact-api/index') -const Config = require('../config') -// const { nonEncryptedRoutes } = require('../../../utils/protectedRoutes') /** * @typedef {import('../contact-api/SimpleGUN').GUNNode} GUNNode @@ -492,579 +486,6 @@ const freshGun = () => { } } -/** - * @param {string} token - * @returns {Promise} - */ -const isValidToken = async token => { - const validation = await auth.validateToken(token) - - if (typeof validation !== 'object') { - return false - } - - if (validation === null) { - return false - } - - if (typeof validation.valid !== 'boolean') { - return false - } - - return validation.valid -} - -/** - * @param {string} token - * @throws {Error} If the token is invalid - * @returns {Promise} - */ -const throwOnInvalidToken = async token => { - const isValid = await isValidToken(token) - - if (!isValid) { - throw new Error('Token expired.') - } -} - -class Mediator { - /** - * @param {Readonly} socket - */ - constructor(socket) { - this.socket = this.encryptSocketInstance(socket) - - this.connected = true - - this.socket.on('disconnect', this.onDisconnect) - - this.socket.on(Action.ACCEPT_REQUEST, this.acceptRequest) - this.socket.on( - Action.GENERATE_NEW_HANDSHAKE_NODE, - this.generateHandshakeNode - ) - this.socket.on('GENERATE_ORDER_ADDRESS', this.generateOrderAddress) - this.socket.on('INIT_FEED_WALL', this.initWall) - this.socket.on(Action.SEND_HANDSHAKE_REQUEST, this.sendHandshakeRequest) - this.socket.on( - Action.SEND_HANDSHAKE_REQUEST_WITH_INITIAL_MSG, - this.sendHRWithInitialMsg - ) - this.socket.on(Action.SEND_MESSAGE, this.sendMessage) - - this.socket.on(Action.SEND_PAYMENT, this.sendPayment) - - this.socket.on(Action.DISCONNECT, this.disconnect) - - this.socket.on(Event.ON_CHATS, this.onChats) - - this.socket.on(Event.ON_HANDSHAKE_ADDRESS, this.onHandshakeAddress) - this.socket.on(Event.ON_RECEIVED_REQUESTS, this.onReceivedRequests) - this.socket.on(Event.ON_SENT_REQUESTS, this.onSentRequests) - - this.socket.on(Event.ON_SEED_BACKUP, this.onSeedBackup) - - this.socket.on(Constants.Misc.IS_GUN_AUTH, this.isGunAuth) - - Object.values(Action).forEach(actionConstant => - this.socket.on(actionConstant, this.setLastSeenApp) - ) - } - - /** @param {SimpleSocket} socket */ - encryptSocketInstance = socket => { - const emit = encryptedEmit(socket) - const on = encryptedOn(socket) - - return { - /** - * @type {SimpleSocket['on']} - */ - on, - /** @type {SimpleSocket['emit']} */ - emit - } - } - - /** @param {{ token: string }} body */ - setLastSeenApp = async body => { - logger.info('setLastSeen Called') - try { - await throwOnInvalidToken(body.token) - await API.Actions.setLastSeenApp() - this.socket.emit(Action.SET_LAST_SEEN_APP, { - ok: true, - msg: null, - origBody: body - }) - } catch (e) { - this.socket.emit(Action.SET_LAST_SEEN_APP, { - ok: false, - msg: e.message, - origBody: body - }) - } - } - - isGunAuth = () => { - try { - const isGunAuth = isAuthenticated() - - this.socket.emit(Constants.Misc.IS_GUN_AUTH, { - ok: true, - msg: { - isGunAuth - }, - origBody: {} - }) - } catch (err) { - this.socket.emit(Constants.Misc.IS_GUN_AUTH, { - ok: false, - msg: err.message, - origBody: {} - }) - } - } - - /** - * @param {Readonly<{ requestID: string , token: string }>} body - */ - acceptRequest = async body => { - try { - const { requestID, token } = body - - await throwOnInvalidToken(token) - - await API.Actions.acceptRequest(requestID, gun, user, mySEA) - - this.socket.emit(Action.ACCEPT_REQUEST, { - ok: true, - msg: null, - origBody: body - }) - } catch (err) { - logger.info(err) - this.socket.emit(Action.ACCEPT_REQUEST, { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - onDisconnect = () => { - this.connected = false - } - - /** - * @param {Readonly<{ token: string }>} body - */ - generateHandshakeNode = async body => { - try { - const { token } = body - - await throwOnInvalidToken(token) - - await API.Actions.generateHandshakeAddress() - - this.socket.emit(Action.GENERATE_NEW_HANDSHAKE_NODE, { - ok: true, - msg: null, - origBody: body - }) - } catch (err) { - logger.info(err) - this.socket.emit(Action.GENERATE_NEW_HANDSHAKE_NODE, { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - /** - * @param {Readonly<{ token: string }>} body - */ - generateOrderAddress = async body => { - try { - const { token } = body - - await throwOnInvalidToken(token) - - await API.Actions.generateOrderAddress(user) - - this.socket.emit('GENERATE_ORDER_ADDRESS', { - ok: true, - msg: null, - origBody: body - }) - } catch (err) { - logger.info(err) - this.socket.emit('GENERATE_ORDER_ADDRESS', { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - /** - * @param {Readonly<{ token: string }>} body - */ - initWall = async body => { - try { - const { token } = body - - await throwOnInvalidToken(token) - - await API.Actions.initWall() - - this.socket.emit('INIT_FEED_WALL', { - ok: true, - msg: null, - origBody: body - }) - } catch (err) { - logger.info(err) - this.socket.emit('INIT_FEED_WALL', { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - /** - * @param {Readonly<{ recipientPublicKey: string , token: string }>} body - */ - sendHandshakeRequest = async body => { - try { - if (Config.SHOW_LOG) { - logger.info('\n') - logger.info('------------------------------') - logger.info('will now try to send a handshake request') - logger.info('------------------------------') - logger.info('\n') - } - - const { recipientPublicKey, token } = body - - await throwOnInvalidToken(token) - - await API.Actions.sendHandshakeRequest( - recipientPublicKey, - gun, - user, - mySEA - ) - - if (Config.SHOW_LOG) { - logger.info('\n') - logger.info('------------------------------') - logger.info('handshake request successfuly sent') - logger.info('------------------------------') - logger.info('\n') - } - - this.socket.emit(Action.SEND_HANDSHAKE_REQUEST, { - ok: true, - msg: null, - origBody: body - }) - } catch (err) { - if (Config.SHOW_LOG) { - logger.info('\n') - logger.info('------------------------------') - logger.info('handshake request send fail: ' + err.message) - logger.info('------------------------------') - logger.info('\n') - } - - this.socket.emit(Action.SEND_HANDSHAKE_REQUEST, { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - /** - * @param {Readonly<{ initialMsg: string , recipientPublicKey: string , token: string }>} body - */ - sendHRWithInitialMsg = async body => { - try { - const { initialMsg, recipientPublicKey, token } = body - - await throwOnInvalidToken(token) - - await API.Actions.sendHRWithInitialMsg( - initialMsg, - recipientPublicKey, - gun, - user, - mySEA - ) - - this.socket.emit(Action.SEND_HANDSHAKE_REQUEST_WITH_INITIAL_MSG, { - ok: true, - msg: null, - origBody: body - }) - } catch (err) { - logger.info(err) - this.socket.emit(Action.SEND_HANDSHAKE_REQUEST_WITH_INITIAL_MSG, { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - /** - * @param {Readonly<{ body: string , recipientPublicKey: string , token: string }>} reqBody - */ - sendMessage = async reqBody => { - try { - const { body, recipientPublicKey, token } = reqBody - - await throwOnInvalidToken(token) - - this.socket.emit(Action.SEND_MESSAGE, { - ok: true, - msg: await API.Actions.sendMessage( - recipientPublicKey, - body, - user, - mySEA - ), - origBody: reqBody - }) - } catch (err) { - logger.info(err) - this.socket.emit(Action.SEND_MESSAGE, { - ok: false, - msg: err.message, - origBody: reqBody - }) - } - } - - /** - * @param {Readonly<{ uuid: string, recipientPub: string, amount: number, memo: string, token: string, feeLimit:number }>} reqBody - */ - sendPayment = async reqBody => { - try { - const { recipientPub, amount, memo, feeLimit, token } = reqBody - - await throwOnInvalidToken(token) - - const preimage = await API.Actions.sendPayment( - recipientPub, - amount, - memo, - feeLimit - ) - - this.socket.emit(Action.SEND_PAYMENT, { - ok: true, - msg: preimage, - origBody: reqBody - }) - } catch (err) { - logger.info(err) - this.socket.emit(Action.SEND_PAYMENT, { - ok: false, - msg: err.message, - origBody: reqBody - }) - } - } - - ////////////////////////////////////////////////////////////////////////////// - - /** - * @param {Readonly<{ token: string }>} body - */ - onChats = async body => { - try { - const { token } = body - - // logger.info('ON_CHATS', body) - - await throwOnInvalidToken(token) - - API.Events.onChats(chats => { - if (Config.SHOW_LOG) { - logger.info('---chats---') - logger.info(JSON.stringify(chats)) - logger.info('-----------------------') - } - - this.socket.emit(Event.ON_CHATS, { - msg: chats, - ok: true, - origBody: body - }) - }) - } catch (err) { - logger.info(err) - this.socket.emit(Event.ON_CHATS, { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - /** - * @param {Readonly<{ token: string }>} body - */ - onHandshakeAddress = async body => { - try { - const { token } = body - - await throwOnInvalidToken(token) - - API.Events.onCurrentHandshakeAddress(addr => { - if (Config.SHOW_LOG) { - logger.info('---addr---') - logger.info(addr || 'null or empty string') - logger.info('-----------------------') - } - - this.socket.emit(Event.ON_HANDSHAKE_ADDRESS, { - ok: true, - msg: addr, - origBody: body - }) - }, user) - } catch (err) { - logger.info(err) - this.socket.emit(Event.ON_HANDSHAKE_ADDRESS, { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - /** - * @param {Readonly<{ token: string }>} body - */ - onReceivedRequests = async body => { - try { - const { token } = body - - await throwOnInvalidToken(token) - - API.Events.onSimplerReceivedRequests(receivedRequests => { - this.socket.emit(Event.ON_RECEIVED_REQUESTS, { - msg: receivedRequests, - ok: true, - origBody: body - }) - }) - } catch (err) { - logger.info(err) - this.socket.emit(Event.ON_RECEIVED_REQUESTS, { - msg: err.message, - ok: false, - origBody: body - }) - } - } - - onSentRequestsSubbed = false - - /** - * @param {Readonly<{ token: string }>} body - */ - onSentRequests = async body => { - try { - const { token } = body - - await throwOnInvalidToken(token) - - if (!this.onSentRequestsSubbed) { - this.onSentRequestsSubbed = true - - API.Events.onSimplerSentRequests( - debounce(sentRequests => { - // logger.info( - // `new Reqss in mediator: ${JSON.stringify(sentRequests)}` - // ) - this.socket.emit(Event.ON_SENT_REQUESTS, { - msg: sentRequests, - ok: true, - origBody: body - }) - }, 1000) - ) - } - } catch (err) { - logger.info(err) - this.socket.emit(Event.ON_SENT_REQUESTS, { - msg: err.message, - ok: false, - origBody: body - }) - } - } - - /** - * @param {Readonly<{ token: string }>} body - */ - onSeedBackup = async body => { - try { - const { token } = body - - await throwOnInvalidToken(token) - - await API.Events.onSeedBackup( - seedBackup => { - this.socket.emit(Event.ON_SEED_BACKUP, { - ok: true, - msg: seedBackup, - origBody: body - }) - }, - user, - mySEA - ) - } catch (err) { - logger.info(err) - this.socket.emit(Event.ON_SEED_BACKUP, { - ok: false, - msg: err.message, - origBody: body - }) - } - } - - /** @param {Readonly<{ pub: string, token: string }>} body */ - disconnect = async body => { - try { - const { pub, token } = body - - await throwOnInvalidToken(token) - - await API.Actions.disconnect(pub) - - this.socket.emit(Action.DISCONNECT, { - ok: true, - msg: null, - origBody: body - }) - } catch (err) { - this.socket.emit(Action.DISCONNECT, { - ok: false, - msg: err.message, - origBody: body - }) - } - } -} - /** * Creates an user for gun. Returns a promise containing the public key of the * newly created user. @@ -1183,25 +604,9 @@ const register = async (alias, pass) => { }) } -/** - * @param {SimpleSocket} socket - * @throws {Error} If gun is not authenticated or is in the process of - * authenticating. Use `isAuthenticating()` and `isAuthenticated()` to check for - * this first. - * @returns {Mediator} - */ -const createMediator = socket => { - // if (isAuthenticating() || !isAuthenticated()) { - // throw new Error("Gun must be authenticated to create a Mediator"); - // } - - return new Mediator(socket) -} - module.exports = { authenticate, logoff, - createMediator, isAuthenticated, isAuthenticating, isRegistering,