fix: retain masterkey on non-logout error scenarios and refresh on db hit miss

This commit is contained in:
ramvignesh-b
2026-04-15 16:57:03 +05:30
parent ef545e9e2b
commit fd64578a17
4 changed files with 89 additions and 16 deletions
+30 -9
View File
@@ -4,6 +4,7 @@ import { endpoints } from "../config/endpoints";
import type { UserProfile } from "../store/useAuthStore";
import { useAuthStore } from "../store/useAuthStore";
import { useKeyStore } from "../store/useKeyStore";
import { CryptoUtils } from "../utils/crypto";
import {
clearMasterKey,
loadMasterKey,
@@ -40,9 +41,17 @@ export const useAuth = () => {
};
const initialize = useCallback(async () => {
const { accessToken, user, setAuth, clearAuth, setInitializing } =
const { accessToken, user, setAuth, setInitializing } =
useAuthStore.getState();
// Restore master key from IndexedDB
try {
const masterKey = await loadMasterKey();
if (masterKey) setMasterKey(masterKey);
} catch {
console.error("Master key restoration failed");
}
// If session in memory, don't trigger refresh/me again
if (accessToken && user) {
setInitializing(false);
@@ -50,23 +59,34 @@ export const useAuth = () => {
}
try {
// try refresh
// try session refresh
const { data: refreshData } = await publicApi.post(endpoints.REFRESH);
const { data: userData } = await api.get(endpoints.ME, {
headers: { Authorization: `Bearer ${refreshData.access}` },
});
setAuth(refreshData.access, userData);
// restore master key from IndexedDB
const masterKey = await loadMasterKey();
if (masterKey) setMasterKey(masterKey);
} catch {
clearAuth();
setMasterKey(null);
await clearMasterKey();
// grace for temporary network errors
} finally {
setInitializing(false);
}
}, [setMasterKey]);
const unlock = async (password: string) => {
if (!user) return;
try {
const { masterKey } = await CryptoUtils.deriveKeyBundle(
password,
user.email,
);
await saveMasterKey(masterKey);
setMasterKey(masterKey);
} catch {
console.error("Master key restoration failed");
}
};
return {
isAuthenticated,
user,
@@ -74,5 +94,6 @@ export const useAuth = () => {
setAuthStore,
logout,
initialize,
unlock,
};
};