Skip to content

feat: encrypt tokens using safe storage api #1800

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 1, 2025
Merged
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
11 changes: 10 additions & 1 deletion src/main/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { app, globalShortcut, ipcMain as ipc } from 'electron';
import { app, globalShortcut, ipcMain as ipc, safeStorage } from 'electron';
import log from 'electron-log';
import { menubar } from 'menubar';

Expand Down Expand Up @@ -169,6 +169,15 @@ app.whenReady().then(async () => {
});
});

// Safe Storage
ipc.handle(namespacedEvent('safe-storage-encrypt'), (_, settings) => {
return safeStorage.encryptString(settings).toString('base64');
});

ipc.handle(namespacedEvent('safe-storage-decrypt'), (_, settings) => {
return safeStorage.decryptString(Buffer.from(settings, 'base64'));
});

// Handle gitify:// custom protocol URL events for OAuth 2.0 callback
app.on('open-url', (event, url) => {
event.preventDefault();
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/__mocks__/electron.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ module.exports = {
return Promise.resolve('darwin');
case namespacedEvent('version'):
return Promise.resolve('0.0.1');
case namespacedEvent('safe-storage-encrypt'):
return Promise.resolve('encrypted');
case namespacedEvent('safe-storage-decrypt'):
return Promise.resolve('decrypted');
default:
return Promise.reject(new Error(`Unknown channel: ${channel}`));
}
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/context/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ describe('renderer/context/App.tsx', () => {
expect(apiRequestAuthMock).toHaveBeenCalledWith(
'https://api.github.com/user',
'GET',
'123-456',
'encrypted',
);
});
});
Expand Down
14 changes: 14 additions & 0 deletions src/renderer/context/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
type Status,
type SystemSettingsState,
Theme,
type Token,
} from '../types';
import type { Notification } from '../typesGitHub';
import { headNotifications } from '../utils/api/client';
Expand All @@ -44,6 +45,8 @@ import {
removeAccount,
} from '../utils/auth/utils';
import {
decryptValue,
encryptValue,
setAlternateIdleIcon,
setAutoLaunch,
setKeyboardShortcut,
Expand Down Expand Up @@ -292,6 +295,17 @@ export const AppProvider = ({ children }: { children: ReactNode }) => {

// Refresh account data on app start
for (const account of existing.auth.accounts) {
/**
* Check if the account is using an encrypted token.
* If not encrypt it and save it.
*/
try {
await decryptValue(account.token);
} catch (err) {
const encryptedToken = await encryptValue(account.token);
account.token = encryptedToken as Token;
}

await refreshAccount(account);
}
}
Expand Down
26 changes: 13 additions & 13 deletions src/renderer/utils/api/__snapshots__/client.test.ts.snap

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/renderer/utils/api/__snapshots__/request.test.ts.snap

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions src/renderer/utils/api/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import axios, {
type Method,
} from 'axios';

import { logError } from '../../../shared/logger';
import { logError, logWarn } from '../../../shared/logger';
import type { Link, Token } from '../../types';
import { decryptValue } from '../comms';
import { getNextURLFromLinkHeader } from './utils';

/**
Expand Down Expand Up @@ -44,8 +45,16 @@ export async function apiRequestAuth(
data = {},
fetchAllRecords = false,
): AxiosPromise | null {
let apiToken = token;
// TODO - Remove this try-catch block in a future release
try {
apiToken = (await decryptValue(token)) as Token;
} catch (err) {
logWarn('apiRequestAuth', 'Token is not yet encrypted');
}

axios.defaults.headers.common.Accept = 'application/json';
axios.defaults.headers.common.Authorization = `token ${token}`;
axios.defaults.headers.common.Authorization = `token ${apiToken}`;
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.defaults.headers.common['Cache-Control'] = shouldRequestWithNoCache(url)
? 'no-cache'
Expand Down
8 changes: 4 additions & 4 deletions src/renderer/utils/auth/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ describe('renderer/utils/auth/utils.ts', () => {
hostname: 'github.com' as Hostname,
method: 'Personal Access Token',
platform: 'GitHub Cloud',
token: '123-456' as Token,
token: 'encrypted' as Token,
user: mockGitifyUser,
version: 'latest',
},
Expand All @@ -211,7 +211,7 @@ describe('renderer/utils/auth/utils.ts', () => {
hostname: 'github.com' as Hostname,
method: 'OAuth App',
platform: 'GitHub Cloud',
token: '123-456' as Token,
token: 'encrypted' as Token,
user: mockGitifyUser,
version: 'latest',
},
Expand Down Expand Up @@ -243,7 +243,7 @@ describe('renderer/utils/auth/utils.ts', () => {
hostname: 'github.gitify.io' as Hostname,
method: 'Personal Access Token',
platform: 'GitHub Enterprise Server',
token: '123-456' as Token,
token: 'encrypted' as Token,
user: mockGitifyUser,
version: '3.0.0',
},
Expand All @@ -263,7 +263,7 @@ describe('renderer/utils/auth/utils.ts', () => {
hostname: 'github.gitify.io' as Hostname,
method: 'OAuth App',
platform: 'GitHub Enterprise Server',
token: '123-456' as Token,
token: 'encrypted' as Token,
user: mockGitifyUser,
version: '3.0.0',
},
Expand Down
5 changes: 3 additions & 2 deletions src/renderer/utils/auth/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import type {
import type { UserDetails } from '../../typesGitHub';
import { getAuthenticatedUser } from '../api/client';
import { apiRequest } from '../api/request';
import { openExternalLink } from '../comms';
import { encryptValue, openExternalLink } from '../comms';
import { Constants } from '../constants';
import { getPlatformFromHostname } from '../helpers';
import type { AuthMethod, AuthResponse, AuthTokenResponse } from './types';
Expand Down Expand Up @@ -109,12 +109,13 @@ export async function addAccount(
hostname: Hostname,
): Promise<AuthState> {
const accountList = auth.accounts;
const encryptedToken = await encryptValue(token);

let newAccount = {
hostname: hostname,
method: method,
platform: getPlatformFromHostname(hostname),
token: token,
token: encryptedToken,
} as Account;

newAccount = await refreshAccount(newAccount);
Expand Down
20 changes: 20 additions & 0 deletions src/renderer/utils/comms.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { namespacedEvent } from '../../shared/events';
import { mockSettings } from '../__mocks__/state-mocks';
import type { Link } from '../types';
import {
decryptValue,
encryptValue,
getAppVersion,
hideWindow,
openExternalLink,
Expand Down Expand Up @@ -68,6 +70,24 @@ describe('renderer/utils/comms.ts', () => {
expect(ipcRenderer.invoke).toHaveBeenCalledWith(namespacedEvent('version'));
});

it('should encrypt a value', async () => {
await encryptValue('value');
expect(ipcRenderer.invoke).toHaveBeenCalledTimes(1);
expect(ipcRenderer.invoke).toHaveBeenCalledWith(
namespacedEvent('safe-storage-encrypt'),
'value',
);
});

it('should decrypt a value', async () => {
await decryptValue('value');
expect(ipcRenderer.invoke).toHaveBeenCalledTimes(1);
expect(ipcRenderer.invoke).toHaveBeenCalledWith(
namespacedEvent('safe-storage-decrypt'),
'value',
);
});

it('should quit the app', () => {
quitApp();
expect(ipcRenderer.send).toHaveBeenCalledTimes(1);
Expand Down
14 changes: 14 additions & 0 deletions src/renderer/utils/comms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ export async function getAppVersion(): Promise<string> {
return await ipcRenderer.invoke(namespacedEvent('version'));
}

export async function encryptValue(value: string): Promise<string> {
return await ipcRenderer.invoke(
namespacedEvent('safe-storage-encrypt'),
value,
);
}

export async function decryptValue(value: string): Promise<string> {
return await ipcRenderer.invoke(
namespacedEvent('safe-storage-decrypt'),
value,
);
}

export function quitApp(): void {
ipcRenderer.send(namespacedEvent('quit'));
}
Expand Down