Skip to content

Commit 05924a0

Browse files
martinkaintasperonczyk
authored andcommitted
refactor: rename passwordKey to encryptedData
1 parent 1efa6ac commit 05924a0

File tree

16 files changed

+177
-157
lines changed

16 files changed

+177
-157
lines changed

src/background/bgPopupHandler.ts

+17-12
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type {
33
Dictionary,
44
IPopupProps,
55
PopupType,
6-
IExportedKey,
6+
IExportedEncryptionData,
77
} from '@/types';
88

99
interface IPopupConfigNoActions {
@@ -21,6 +21,11 @@ const PLATFORM = process.env.PLATFORM as 'web' | 'extension' | 'ionic';
2121
const RUNNING_IN_TESTS = !!process.env.RUNNING_IN_TESTS;
2222
const IS_EXTENSION = PLATFORM === 'extension' && !RUNNING_IN_TESTS;
2323

24+
const SESSION_STORAGE_KEYS = {
25+
encryptionData: 'encryptionData',
26+
sessionExpires: 'sessionExpires',
27+
};
28+
2429
const POPUP_TYPE_CONNECT = 'connectConfirm';
2530

2631
const popups: Dictionary<IPopupConfigNoActions> = {};
@@ -84,24 +89,24 @@ export const removePopup = (id: string) => delete popups[id];
8489

8590
export const getPopup = (id: string): IPopupConfigNoActions => popups[id];
8691

87-
export const setSessionExpiration = async (expires: number) => {
88-
await storageSession.set({ sessionExpires: expires });
92+
export const setSessionExpiration = async (sessionExpires: number) => {
93+
await storageSession.set({ sessionExpires });
8994
};
9095

91-
export const getSession = async (): Promise<IExportedKey | null> => {
96+
export const getSessionEncryptionData = async (): Promise<IExportedEncryptionData | null> => {
9297
try {
93-
const { sessionExpires } = await storageSession.get('sessionExpires');
94-
if (sessionExpires < Date.now() || !sessionExpires) {
95-
await storageSession.remove('sessionKey');
98+
const { sessionExpires } = await storageSession.get(SESSION_STORAGE_KEYS.sessionExpires);
99+
if (!sessionExpires || sessionExpires < Date.now()) {
100+
await storageSession.remove(SESSION_STORAGE_KEYS.encryptionData);
96101
return null;
97102
}
98103

99-
const { sessionKey } = await storageSession.get('sessionKey');
100-
if (sessionKey) {
104+
const { encryptionData } = await storageSession.get(SESSION_STORAGE_KEYS.encryptionData);
105+
if (encryptionData) {
101106
return {
102-
key: Buffer.from(sessionKey.key).toString('base64'),
103-
salt: Buffer.from(sessionKey.salt).toString('base64'),
104-
iv: Buffer.from(sessionKey.iv).toString('base64'),
107+
key: Buffer.from(encryptionData.key).toString('base64'),
108+
salt: Buffer.from(encryptionData.salt).toString('base64'),
109+
iv: Buffer.from(encryptionData.iv).toString('base64'),
105110
};
106111
}
107112
} catch (error) { /** NOOP */ }

src/background/index.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
openPopup,
44
removePopup,
55
getPopup,
6-
getSession,
6+
getSessionEncryptionData,
77
setSessionExpiration,
88
} from './bgPopupHandler';
99
import { updateDynamicRules } from './redirectRule';
@@ -37,9 +37,9 @@ import { updateDynamicRules } from './redirectRule';
3737
function handleMessage(msg: IBackgroundMessageData, _: any, sendResponse: Function) {
3838
if (msg.target === 'background') {
3939
// Handle session methods independently because params are not set
40-
if (msg.method === 'getSessionKey') {
41-
getSession().then((sessionKey) => {
42-
sendResponse(sessionKey);
40+
if (msg.method === 'getSessionEncryptionData') {
41+
getSessionEncryptionData().then((encryptionData) => {
42+
sendResponse(encryptionData);
4343
});
4444
return true;
4545
}

src/composables/accounts.ts

+46-38
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type {
77
AccountType,
88
IAccount,
99
IAccountRaw,
10-
IKey,
10+
IEncryptionData,
1111
IFormSelectOption,
1212
Protocol,
1313
ProtocolRecord,
@@ -31,8 +31,9 @@ import {
3131
encrypt,
3232
endSession,
3333
excludeFalsy,
34-
generateKey,
35-
getSessionKey,
34+
restoreEncryptionData,
35+
initializeEncryptionData,
36+
getSessionEncryptionData,
3637
prepareAccountSelectOptions,
3738
startSession,
3839
watchUntilTruthy,
@@ -60,7 +61,7 @@ const {
6061

6162
const areAccountsRestored = ref(false);
6263
const isMnemonicRestored = ref(false);
63-
const passwordKey = ref<IKey | null>(null);
64+
const encryptionData = ref<IEncryptionData | null>();
6465

6566
const mnemonic = useSecureStorageRef<string>(
6667
'',
@@ -73,7 +74,7 @@ const mnemonic = useSecureStorageRef<string>(
7374
],
7475
onRestored: async (val) => {
7576
const hasStoredMnemonic = (
76-
await WalletStorage.get(STORAGE_KEYS.mnemonic)
77+
WalletStorage.get(STORAGE_KEYS.mnemonic)
7778
|| await SecureMobileStorage.get(STORAGE_KEYS.mnemonic)
7879
);
7980
isMnemonicRestored.value = !!val || !hasStoredMnemonic;
@@ -252,22 +253,27 @@ export function useAccounts() {
252253
/**
253254
* Setting/Resetting the password key logs the user in/out.
254255
*/
255-
function setPasswordKey(key: IKey | null) {
256-
passwordKey.value = key;
256+
function setEncryptionData(newEncryptionData: IEncryptionData | null) {
257+
encryptionData.value = newEncryptionData;
257258
if (IS_EXTENSION) {
258-
if (key) {
259-
startSession(key, secureLoginTimeout.value);
259+
if (newEncryptionData) {
260+
startSession(newEncryptionData, secureLoginTimeout.value);
260261
} else {
261262
endSession();
262263
}
263264
}
264265
}
265266

267+
async function getEncryptionData() {
268+
await watchUntilTruthy(encryptionData);
269+
return encryptionData.value;
270+
}
271+
266272
async function openLoginModal() {
267273
setLoaderVisible(true);
268-
const sessionKey = await getSessionKey();
269-
if (sessionKey) {
270-
setPasswordKey(sessionKey);
274+
const sessionEncryptionData = await getSessionEncryptionData();
275+
if (sessionEncryptionData) {
276+
setEncryptionData(sessionEncryptionData);
271277
const { getAeSdk } = useAeSdk();
272278
await getAeSdk();
273279
setLoaderVisible(false);
@@ -278,26 +284,27 @@ export function useAccounts() {
278284
const { openModal } = useModals();
279285

280286
await openModal(MODAL_PASSWORD_LOGIN);
281-
if (!passwordKey.value) {
282-
throw new Error('passwordKey was not set after login.');
287+
if (!encryptionData.value) {
288+
throw new Error('encryptionData was not set after login.');
283289
}
284290
}
285291

286-
async function setPassword(newMnemonic: string, password: string) {
287-
const key = await generateKey(password);
288-
const encryptedMnemonic = await encrypt(key, newMnemonic);
292+
async function setPasswordAndEncryptMnemonic(newMnemonic: string, password: string) {
293+
const newEncryptionData = await initializeEncryptionData(password);
294+
const encryptedMnemonic = await encrypt(newEncryptionData, newMnemonic);
289295
WalletStorage.set(STORAGE_KEYS.mnemonic, encryptedMnemonic);
290-
291-
// Saved key needs to be generated from the password and the encrypted mnemonic
292-
setPasswordKey(await generateKey(password, encryptedMnemonic));
296+
setEncryptionData(newEncryptionData);
293297
}
294298

295299
async function updatePassword(currentPassword: string, newPassword: string) {
296-
const encryptedMnemonic = await WalletStorage.get<string>(STORAGE_KEYS.mnemonic) || undefined;
297-
const key = await generateKey(currentPassword, encryptedMnemonic);
298-
const decryptedMnemonic = await decrypt(key, encryptedMnemonic!);
300+
const encryptedMnemonic = WalletStorage.get<string>(STORAGE_KEYS.mnemonic);
301+
if (!encryptedMnemonic) {
302+
throw new Error('Mnemonic not found.');
303+
}
304+
const restoredEncryptionData = await restoreEncryptionData(currentPassword, encryptedMnemonic);
305+
const decryptedMnemonic = await decrypt(restoredEncryptionData, encryptedMnemonic);
299306
if (decryptedMnemonic) {
300-
await setPassword(decryptedMnemonic, newPassword);
307+
await setPasswordAndEncryptMnemonic(decryptedMnemonic, newPassword);
301308
} else {
302309
throw new Error('Incorrect password.');
303310
}
@@ -310,10 +317,10 @@ export function useAccounts() {
310317
isRestoredWallet: isRestored,
311318
});
312319

313-
await setPassword(newMnemonic, password);
320+
await setPasswordAndEncryptMnemonic(newMnemonic, password);
314321
}
315322

316-
async function setMnemonic(newMnemonic: string, isRestored = false) {
323+
async function setMnemonicAndInitializePassword(newMnemonic: string, isRestored = false) {
317324
if (!IS_MOBILE_APP) {
318325
await openSetPasswordModal(newMnemonic, isRestored).catch(() => {
319326
throw new Error('Password was not set.');
@@ -323,7 +330,7 @@ export function useAccounts() {
323330
}
324331

325332
async function setGeneratedMnemonic() {
326-
await setMnemonic(generateMnemonic()).catch(() => {
333+
await setMnemonicAndInitializePassword(generateMnemonic()).catch(() => {
327334
throw new Error('Mnemonic was not set.');
328335
});
329336
}
@@ -366,12 +373,12 @@ export function useAccounts() {
366373
activeAccountGlobalIdx.value = 0;
367374
}
368375

369-
async function waitForSessionKey() {
376+
async function waitForSessionEncryptionData() {
370377
await new Promise<void>((resolve) => {
371378
const interval = setInterval(async () => {
372-
const key = await getSessionKey();
373-
if (key) {
374-
setPasswordKey(key);
379+
const sessionEncryptionData = await getSessionEncryptionData();
380+
if (sessionEncryptionData) {
381+
setEncryptionData(sessionEncryptionData);
375382
clearInterval(interval);
376383
resolve();
377384
}
@@ -382,9 +389,9 @@ export function useAccounts() {
382389
(async () => {
383390
if (!composableInitialized) {
384391
composableInitialized = true;
385-
const storedMnemonic = await WalletStorage.get(STORAGE_KEYS.mnemonic);
392+
const storedMnemonic = WalletStorage.get(STORAGE_KEYS.mnemonic);
386393
if (
387-
!passwordKey.value
394+
!encryptionData.value
388395
&& !IS_MOBILE_APP
389396
// If the mnemonic is stored but is not valid as plaintext
390397
// it means that user is trying to access an existing & encrypted wallet
@@ -393,8 +400,8 @@ export function useAccounts() {
393400
await openLoginModal();
394401
}
395402

396-
if (IS_OFFSCREEN_TAB && !passwordKey.value) {
397-
await waitForSessionKey();
403+
if (IS_OFFSCREEN_TAB && !encryptionData.value) {
404+
await waitForSessionEncryptionData();
398405
return;
399406
}
400407

@@ -420,13 +427,14 @@ export function useAccounts() {
420427
isLoggedIn,
421428
isActiveAccountAirGap,
422429
mnemonic,
423-
passwordKey,
430+
encryptionData,
424431
mnemonicSeed,
425432
protocolsInUse,
426433
openLoginModal,
427434
discoverAccounts,
428435
isLocalAccountAddress,
429436
addRawAccount,
437+
getEncryptionData,
430438
getAccountByAddress,
431439
getAccountByGlobalIdx,
432440
getLastActiveProtocolAccount,
@@ -435,8 +443,8 @@ export function useAccounts() {
435443
setActiveAccountByGlobalIdx,
436444
setActiveAccountByProtocolAndIdx,
437445
setActiveAccountByProtocol,
438-
setMnemonic,
439-
setPasswordKey,
446+
setMnemonicAndInitializePassword,
447+
setEncryptionData,
440448
updatePassword,
441449
setGeneratedMnemonic,
442450
resetAccounts,

src/composables/auth.ts

+8-8
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
MODAL_ENABLE_BIOMETRIC_LOGIN,
1313
MODAL_SECURE_LOGIN,
1414
} from '@/constants';
15-
import { authenticateWithPassword, getSessionKey, watchUntilTruthy } from '@/utils';
15+
import { authenticateWithPassword, getSessionEncryptionData, watchUntilTruthy } from '@/utils';
1616
import { useUi } from './ui';
1717
import { useModals } from './modals';
1818
import { useAccounts } from './accounts';
@@ -36,8 +36,8 @@ export const useAuth = createCustomScopedComposable(() => {
3636
const { openModal } = useModals();
3737
const {
3838
isLoggedIn,
39-
passwordKey,
40-
setPasswordKey,
39+
encryptionData,
40+
setEncryptionData,
4141
openLoginModal,
4242
} = useAccounts();
4343

@@ -87,7 +87,7 @@ export const useAuth = createCustomScopedComposable(() => {
8787
}
8888
} else if (!IS_MOBILE_APP) {
8989
return authenticateWithPassword(password!).then((key) => {
90-
setPasswordKey(key);
90+
setEncryptionData(key);
9191
isAuthenticated.value = true;
9292
});
9393
}
@@ -96,12 +96,12 @@ export const useAuth = createCustomScopedComposable(() => {
9696

9797
async function logout() {
9898
if (IS_EXTENSION) {
99-
const sessionKey = await getSessionKey();
100-
if (sessionKey) {
99+
const sessionEncryptionData = await getSessionEncryptionData();
100+
if (sessionEncryptionData) {
101101
return;
102102
}
103103
}
104-
setPasswordKey(null);
104+
setEncryptionData(null);
105105
isAuthenticated.value = false;
106106
}
107107

@@ -110,7 +110,7 @@ export const useAuth = createCustomScopedComposable(() => {
110110
isAuthenticating.value = true;
111111
if (isBiometricLoginEnabled.value && await checkBiometricLoginAvailability()) {
112112
await openModal(MODAL_SECURE_LOGIN);
113-
} else if (!IS_MOBILE_APP && !passwordKey.value) {
113+
} else if (!IS_MOBILE_APP && !encryptionData.value) {
114114
await openLoginModal();
115115
}
116116
// wait before resetting isAuthenticated so that app doesn't register a false app resume event

0 commit comments

Comments
 (0)