diff --git a/README.md b/README.md index 2822475b..22f10919 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ Use the following environment variables for testing purposes: The user data folders for different operating systems are as follows: -- **Windows**: `%APPDATA%/nethlink/` +- **Windows**: `%LOCALAPPDATA%/nethlink/` (`%APPDATA%/nethlink/` up to version 1.6.1: on the first start the app copies its data from there) - **Linux**: `~/.config/nethlink/` - **macOS**: `~/Library/Application Support/nethlink/` diff --git a/src/main/classes/controllers/AccountController.ts b/src/main/classes/controllers/AccountController.ts index f433d48d..9a470011 100644 --- a/src/main/classes/controllers/AccountController.ts +++ b/src/main/classes/controllers/AccountController.ts @@ -107,7 +107,18 @@ export class AccountController { const psw: Buffer = Buffer.from( authAppData.lastUserCryptPsw as Uint8Array, ) - const decryptString = safeStorage.decryptString(psw) + let decryptString: string + try { + decryptString = safeStorage.decryptString(psw) + } catch (e) { + // e.g. the blob was written on another PC or by another Windows + // user (redirected or synced user data folder) + Log.warning( + 'auto login failed: cannot decrypt the saved password with safeStorage', + e, + ) + return false + } const _accountData = JSON.parse(decryptString) const password = _accountData.password diff --git a/src/main/lib/localUserData.ts b/src/main/lib/localUserData.ts new file mode 100644 index 00000000..99b285af --- /dev/null +++ b/src/main/lib/localUserData.ts @@ -0,0 +1,71 @@ +import { app } from 'electron' +import path from 'path' +import fs from 'fs' +import { Log } from '@shared/utils/logger' + +// Files copied from the old roaming folder on the first start: the app state +// and the renderer localStorage, which keeps the audio devices and the ringtone. +// Chromium caches are left behind: they are rebuilt on their own. +const MIGRATED_ENTRIES = [ + /^user_data\d*\.json(\.bak)?$/, + /^available_user_data\.json(\.bak)?$/, + /^Local Storage$/, +] + +/** + * On Windows keep the user data in %LOCALAPPDATA% instead of the default + * %APPDATA% (Roaming). + * + * The roaming folder can be redirected or synced between the PCs of the same + * user (e.g. office PC and notebook). The password is encrypted with + * safeStorage, that is DPAPI bound to the machine and the Windows user, so a + * blob written on one PC may not decrypt on the other, and the PCs overwrite + * each other's state. A local folder belongs to the machine only. + * + * It must run before anything reads app.getPath('userData'), the store reads + * it when its module is loaded: import this module first in main.ts. + */ +function useLocalUserData() { + if (process.platform !== 'win32' || !process.env['LOCALAPPDATA']) { + return + } + const roamingPath = app.getPath('userData') + const localPath = path.join( + process.env['LOCALAPPDATA'], + path.basename(roamingPath), + ) + if (path.resolve(roamingPath) === path.resolve(localPath)) { + return + } + if (!fs.existsSync(localPath)) { + migrate(roamingPath, localPath) + } + app.setPath('userData', localPath) +} + +function migrate(roamingPath: string, localPath: string) { + fs.mkdirSync(localPath, { recursive: true }) + if (!fs.existsSync(roamingPath)) { + return + } + for (const entry of fs.readdirSync(roamingPath)) { + if (!MIGRATED_ENTRIES.some((re) => re.test(entry))) { + continue + } + try { + fs.cpSync(path.join(roamingPath, entry), path.join(localPath, entry), { + recursive: true, + }) + } catch (e: any) { + // a partial copy only costs a new sign in or the device choices + Log.warning('user data migration: cannot copy', entry, e?.code || e) + } + } +} + +try { + useLocalUserData() +} catch (e: any) { + // keep the default roaming folder rather than not starting at all + Log.warning('cannot use the local user data folder', e?.code || e) +} diff --git a/src/main/main.ts b/src/main/main.ts index c746d1e5..ac4318b4 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -1,3 +1,5 @@ +// must stay the first import: it moves the user data folder before anything reads it +import './lib/localUserData' import { app, ipcMain, @@ -232,8 +234,9 @@ function startLogger() { }) isDev() && console.log(message) } - ipcMain.on('log-message', (e, message) => { - if (message && isDev()) logOnFile(message) + // Log already filters by level: info and debug only in dev, warnings and errors always + ipcMain.on('log-message', (_e, message) => { + if (message) logOnFile(message) }) // Always log PhoneIsland renderer messages (for audio diagnostics in production) ipcMain.on('phone-island-log', (_e, message) => { diff --git a/src/shared/utils/logger.ts b/src/shared/utils/logger.ts index 416a0ae5..980fc4a1 100644 --- a/src/shared/utils/logger.ts +++ b/src/shared/utils/logger.ts @@ -1,23 +1,39 @@ import moment from 'moment' import { isDev } from './utils' +type LogLevel = 'INFO' | 'DEBUG' | 'WARNING' | 'ERROR' + +// JSON.stringify turns an Error into {}: keep its name and message +function formatParam(param: any): string { + if (param instanceof Error) { + return `${param.name}: ${param.message}` + } + if (typeof param === 'object') { + try { + return JSON.stringify(param) + } catch { + return String(param) + } + } + return param +} + export class Log { private static log = async ( consoleFunc: (...args: any[]) => void, + level: LogLevel, message?: any, ...optionalParams: any[] ) => { - if (isDev()) { + // in production only warnings and errors reach the log file, so that the + // problems on the customers' PCs can be diagnosed without filling it + if (isDev() || level === 'WARNING' || level === 'ERROR') { const now = moment() const callerLine = '' - let formattedMessage = `${now.format('HH:mm:ss.SSSZ')} ##PAGE## ${callerLine}${ - typeof message === 'object' ? JSON.stringify(message) : message - } ${optionalParams - .map((param) => - typeof param === 'object' ? JSON.stringify(param) : param, - ) - .join(' ')}` + let formattedMessage = `${now.format('HH:mm:ss.SSSZ')} ##PAGE## ${callerLine}${level} ${formatParam( + message, + )} ${optionalParams.map(formatParam).join(' ')}` const pageMaxSplit = 20 const ast = Array(pageMaxSplit) @@ -30,7 +46,8 @@ export class Log { '##PAGE##', `[${'backendpage'.concat(ast).substring(0, pageMaxSplit)}]`, ) - ipcMain.emit('log-message', formattedMessage) + // emit has no real event: the listener reads the message as 2nd argument + ipcMain.emit('log-message', {}, formattedMessage) } catch (err) { formattedMessage = formattedMessage.replace( '##PAGE##',