Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`

Expand Down
13 changes: 12 additions & 1 deletion src/main/classes/controllers/AccountController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
71 changes: 71 additions & 0 deletions src/main/lib/localUserData.ts
Original file line number Diff line number Diff line change
@@ -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)
}
7 changes: 5 additions & 2 deletions src/main/main.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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) => {
Expand Down
35 changes: 26 additions & 9 deletions src/shared/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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##',
Expand Down
Loading