From 96d1beba0ba9283d68a36e781a067bfe9580d124 Mon Sep 17 00:00:00 2001 From: "anton.buksa" Date: Mon, 4 Mar 2024 11:03:53 +0100 Subject: [PATCH] fix team handlers --- src/common/communication.ts | 3 +- src/main/app/initialize.ts | 68 +++++++++++++++++---------------- src/main/preload/externalAPI.ts | 5 +-- src/main/tokenManager.ts | 39 ++++++++++--------- src/main/views/viewManager.ts | 9 +---- 5 files changed, 60 insertions(+), 64 deletions(-) diff --git a/src/common/communication.ts b/src/common/communication.ts index 520e8043..f0aa7a2c 100644 --- a/src/common/communication.ts +++ b/src/common/communication.ts @@ -138,11 +138,10 @@ export const TOKEN_REFRESHED = 'token-refreshed'; export const TOKEN_REQUEST = 'token-request'; export const REFRESH_TOKEN = 'refresh-token'; export const RESET_TOKEN = 'reset-token'; -export const RESET_TEAMS = 'reset-teams'; export const SERVER_ADDED = 'server-added'; export const SERVER_DELETED = 'server-deleted'; export const RESET_AUTH = 'reset-auth'; -export const RESET_TEAMS_HARD = 'reset-teams-hard'; +export const RESET_TEAMS = 'reset-teams-hard'; // Calls export const GET_DESKTOP_SOURCES = 'get-desktop-sources'; diff --git a/src/main/app/initialize.ts b/src/main/app/initialize.ts index a33e6920..7d88a3bd 100644 --- a/src/main/app/initialize.ts +++ b/src/main/app/initialize.ts @@ -3,10 +3,12 @@ import path from 'path'; -import { app, ipcMain, nativeTheme, session } from 'electron'; +import {app, ipcMain, nativeTheme, session} from 'electron'; import isDev from 'electron-is-dev'; -import installExtension, { REACT_DEVELOPER_TOOLS } from 'electron-extension-installer'; -import { init } from '@sentry/electron/main'; +import installExtension, {REACT_DEVELOPER_TOOLS} from 'electron-extension-installer'; +import {init} from '@sentry/electron/main'; + +import {ConfigServer} from 'types/config'; import { FOCUS_BROWSERVIEW, @@ -37,16 +39,16 @@ import { GET_APP_INFO, } from 'common/communication'; import Config from 'common/config'; -import { Logger } from 'common/log'; +import {Logger} from 'common/log'; import AllowProtocolDialog from 'main/allowProtocolDialog'; import AppVersionManager from 'main/AppVersionManager'; import AuthManager from 'main/authManager'; import AutoLauncher from 'main/AutoLauncher'; import updateManager from 'main/autoUpdater'; -import { setupBadge } from 'main/badge'; +import {setupBadge} from 'main/badge'; import CertificateManager from 'main/certificateManager'; -import { configPath, updatePaths } from 'main/constants'; +import {configPath, updatePaths} from 'main/constants'; import CriticalErrorHandler from 'main/CriticalErrorHandler'; import downloadsManager from 'main/downloadsManager'; import i18nManager from 'main/i18nManager'; @@ -59,12 +61,16 @@ import TokenManager from 'main/tokenManager'; import ViewManager from 'main/views/viewManager'; import MainWindow from 'main/windows/mainWindow'; -import { protocols } from '../../../electron-builder.json'; +import {protocols} from '../../../electron-builder.json'; -import { IKDriveAllowedUrls, IKLoginAllowedUrls, IKWelcomeAllowedUrls, KChatTokenWhitelist } from 'common/utils/constants'; +import {IKDriveAllowedUrls, IKLoginAllowedUrls, IKWelcomeAllowedUrls, KChatTokenWhitelist} from 'common/utils/constants'; import ServerManager from 'common/servers/serverManager'; +import buildConfig from 'common/config/buildConfig'; + +import {IKOrigin, devServerUrl, isLocalEnv} from 'common/config/ikConfig'; + import { handleAppBeforeQuit, handleAppBrowserWindowCreated, @@ -110,9 +116,6 @@ import { handleMinimize, handleRestore, } from './windows'; -import { ConfigServer } from 'types/config'; -import buildConfig from 'common/config/buildConfig'; -import { IKOrigin, devServerUrl, isLocalEnv } from 'common/config/ikConfig'; export const mainProtocol = protocols?.[0]?.schemes?.[0]; @@ -290,7 +293,7 @@ function initializeInterCommunicationEventListeners() { ipcMain.handle(GET_CONFIGURATION, handleGetConfiguration); ipcMain.handle(GET_LOCAL_CONFIGURATION, handleGetLocalConfiguration); ipcMain.on(UPDATE_CONFIGURATION, updateConfiguration); - ipcMain.handle(UPDATE_TEAMS, updateTeamsHandler); + ipcMain.on(UPDATE_TEAMS, updateTeamsHandler); ipcMain.handle(GET_DARK_MODE, handleGetDarkMode); ipcMain.on(WINDOW_CLOSE, handleClose); ipcMain.on(WINDOW_MAXIMIZE, handleMaximize); @@ -302,7 +305,6 @@ function initializeInterCommunicationEventListeners() { } function updateTeamsHandler(_: any, servers: ConfigServer[]) { - const [defaultServer] = buildConfig.defaultServers!; const [firstServer] = servers; @@ -325,10 +327,12 @@ function initIKserver() { function initReceivedServer(servers: ConfigServer[]) { ServerManager.removePredefinedServersHandler(true); - servers.forEach(server => { - if (ServerManager.serverNameExist(server)) return + servers.forEach((server) => { + if (ServerManager.serverNameExist(server)) { + return; + } ServerManager.addServer(server); - }) + }); } async function initializeAfterAppReady() { @@ -342,7 +346,7 @@ async function initializeAfterAppReady() { app.setAppUserModelId('Kchat.Desktop'); // Use explicit AppUserModelID const defaultSession = session.defaultSession; - defaultSession.webRequest.onHeadersReceived({ urls: IKLoginAllowedUrls }, + defaultSession.webRequest.onHeadersReceived({urls: IKLoginAllowedUrls}, (d, c) => { if (d.url.includes('/token') && d.responseHeaders) { if (!d.responseHeaders['access-control-allow-origin']) { @@ -369,25 +373,25 @@ async function initializeAfterAppReady() { /* Inject token, for kdrive, images and websocket, rest is handled by the web client. */ - defaultSession.webRequest.onBeforeSendHeaders({ urls: [ + defaultSession.webRequest.onBeforeSendHeaders({urls: [ ...KChatTokenWhitelist, ...IKDriveAllowedUrls, ...IKWelcomeAllowedUrls, - ] }, - (d, c) => { - const authHeader = d.requestHeaders.Authorization ? d.requestHeaders.Authorization : null; - const ikToken = TokenManager.getToken(); - - // No Authorization header or bearer is empty - if ((!authHeader || !authHeader?.split(' ')[1]) && ikToken.token) { - d.requestHeaders.Authorization = `Bearer ${ikToken.token}`; - } + ]}, + (d, c) => { + const authHeader = d.requestHeaders.Authorization ? d.requestHeaders.Authorization : null; + const ikToken = TokenManager.getToken(); + + // No Authorization header or bearer is empty + if ((!authHeader || !authHeader?.split(' ')[1]) && ikToken.token) { + d.requestHeaders.Authorization = `Bearer ${ikToken.token}`; + } - c({ - cancel: false, - requestHeaders: d.requestHeaders, - }); - }, + c({ + cancel: false, + requestHeaders: d.requestHeaders, + }); + }, ); if (process.platform !== 'darwin') { defaultSession.on('spellcheck-dictionary-download-failure', (event, lang) => { diff --git a/src/main/preload/externalAPI.ts b/src/main/preload/externalAPI.ts index d908c8e4..5292d8ef 100644 --- a/src/main/preload/externalAPI.ts +++ b/src/main/preload/externalAPI.ts @@ -57,7 +57,6 @@ import { SERVER_ADDED, SERVER_DELETED, RESET_AUTH, - RESET_TEAMS_HARD, SWITCH_SERVER, } from 'common/communication'; import {IKOrigin} from 'common/config/ikConfig'; @@ -148,7 +147,7 @@ contextBridge.exposeInMainWorld('authManager', { deleteTeam: () => ipcRenderer.invoke(SERVER_DELETED), logout: async () => { await ipcRenderer.invoke(RESET_AUTH); - ipcRenderer.invoke(RESET_TEAMS_HARD); + ipcRenderer.invoke(RESET_TEAMS); }, }); @@ -364,7 +363,7 @@ window.addEventListener('message', ({origin, data = {}}: {origin?: string; data? ipcRenderer.send('call-focus', message); break; } - case RESET_TEAMS: { + case 'reset-teams': { ipcRenderer.send(UPDATE_TEAMS, [{ name: '.', url: IKOrigin, diff --git a/src/main/tokenManager.ts b/src/main/tokenManager.ts index cd6a959a..1e8df1dd 100644 --- a/src/main/tokenManager.ts +++ b/src/main/tokenManager.ts @@ -10,8 +10,9 @@ import log from 'electron-log'; import {UPDATE_PATHS} from 'common/communication'; +import {tokenApiEndpoint} from '../common/config/ikConfig'; + import {tokensStorePath} from './constants'; -import {tokenApiEndpoint} from '../common/config/ikConfig' // import * as Validator from '../common/Validator'; @@ -19,6 +20,7 @@ type Token = { token: string; refreshToken?: string; encrypted?: boolean; + // expiresAt: number; } @@ -39,7 +41,7 @@ export class TokenManager { this.data = {}; this.requestPromise = undefined; this.revokePromise = undefined; - this.safeStorageAvailable = safeStorage.isEncryptionAvailable() + this.safeStorageAvailable = safeStorage.isEncryptionAvailable(); } load = (): Promise> => { @@ -47,9 +49,9 @@ export class TokenManager { let storeStr; try { storeStr = fs.readFileSync(tokensStorePath, 'utf-8'); - let jsonData = (typeof storeStr === 'object' - ? storeStr - : JSON.parse(storeStr)); + const jsonData = (typeof storeStr === 'object' ? + storeStr : + JSON.parse(storeStr)); // jsonData = Validator.validateTokensStore(jsonData); @@ -102,7 +104,7 @@ export class TokenManager { handleStoreToken = (_: IpcMainEvent, message: Token) => { this.data = { token: message.token, - encrypted: true + encrypted: true, }; log.silly('tokenManager.handleStoreToken'); @@ -155,7 +157,7 @@ export class TokenManager { try { const data = JSON.parse(raw) as Record; // eslint-disable-next-line @typescript-eslint/naming-convention - const { access_token, expires_in, refresh_token } = data; + const {access_token, expires_in, refresh_token} = data; this.data = { token: access_token, refreshToken: refresh_token, @@ -280,25 +282,25 @@ export class TokenManager { if (tokenObj.encrypted) { delete tokenObj.encrypted; } - this.save(tokenObj) + this.save(tokenObj); return tokenObj; - - }; + } try { const encryptedString = safeStorage.encryptString(tokenObj.token); const token = { token: encryptedString.toString('base64'), - encrypted: true + encrypted: true, }; this.save(token); + // return decrypted version for operations. return { token: tokenObj.token, - encrypted: true + encrypted: true, }; } catch (error) { - log.error('Token encryption did not work', error) + log.error('Token encryption did not work', error); if (tokenObj.encrypted) { delete tokenObj.encrypted; } @@ -317,16 +319,15 @@ export class TokenManager { } try { - const buffer = Buffer.from(tokenObj.token, 'base64') + const buffer = Buffer.from(tokenObj.token, 'base64'); return { ...tokenObj, - token: safeStorage.decryptString(buffer) - } + token: safeStorage.decryptString(buffer), + }; } catch (error) { - log.error('Token decryption did not work', error) - return tokenObj + log.error('Token decryption did not work', error); + return tokenObj; } - } } diff --git a/src/main/views/viewManager.ts b/src/main/views/viewManager.ts index 0f240782..a7d11d3f 100644 --- a/src/main/views/viewManager.ts +++ b/src/main/views/viewManager.ts @@ -198,14 +198,7 @@ export class ViewManager { } resetTeams = () => { - // TokenManager.reset(); - Config.setServers([{ - name: '.', - url: IKOrigin, - order: 0, - tabs: [{ name: 'TAB_MESSAGING', order: 0, isOpen: true }], - }]); - this.reload(); + ServerManager.reloadFromConfig(); } handleCallJoined = (_: IpcMainEvent, message: any) => {