fix: make encryption key storage SSR-safe to prevent 502 errors
- Add isBrowser() check to key-storage.ts functions - Initialize EncryptionKeyProvider with false and hydrate on mount - Guard getInitialDisplayState against SSR execution
This commit is contained in:
parent
f260e933ca
commit
0fcc66e25d
|
|
@ -52,6 +52,9 @@ function getInitialDisplayState(isKeySet: boolean): DisplayState {
|
|||
if (!isKeySet) {
|
||||
return 'encrypted';
|
||||
}
|
||||
if (typeof window === 'undefined') {
|
||||
return 'encrypted';
|
||||
}
|
||||
const keyString = getStoredKey();
|
||||
return keyString ? 'loading' : 'encrypted';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,10 +27,7 @@ const EncryptionKeyContext = createContext<
|
|||
>(undefined);
|
||||
|
||||
export function EncryptionKeyProvider({ children }: { children: ReactNode }) {
|
||||
const [isKeySet, setIsKeySet] = useState(() => {
|
||||
const key = getStoredKey();
|
||||
return !!key;
|
||||
});
|
||||
const [isKeySet, setIsKeySet] = useState(false);
|
||||
const [encryptedMessageData, setEncryptedMessageData] =
|
||||
useState<EncryptedMessageData | null>(null);
|
||||
|
||||
|
|
@ -56,6 +53,8 @@ export function EncryptionKeyProvider({ children }: { children: ReactNode }) {
|
|||
}
|
||||
|
||||
useEffect(() => {
|
||||
refreshKeyState();
|
||||
|
||||
const interval = setInterval(() => {
|
||||
const key = getStoredKey();
|
||||
setIsKeySet(!!key);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,12 @@
|
|||
const ENCRYPTION_KEY_NAME = 'encryption_key';
|
||||
|
||||
function isBrowser(): boolean {
|
||||
return typeof window !== 'undefined';
|
||||
}
|
||||
|
||||
export function storeKey(key: string, persistent: boolean): void {
|
||||
if (!isBrowser()) return;
|
||||
|
||||
if (persistent) {
|
||||
localStorage.setItem(ENCRYPTION_KEY_NAME, key);
|
||||
} else {
|
||||
|
|
@ -9,6 +15,8 @@ export function storeKey(key: string, persistent: boolean): void {
|
|||
}
|
||||
|
||||
export function getStoredKey(): string | null {
|
||||
if (!isBrowser()) return null;
|
||||
|
||||
return (
|
||||
sessionStorage.getItem(ENCRYPTION_KEY_NAME) ||
|
||||
localStorage.getItem(ENCRYPTION_KEY_NAME)
|
||||
|
|
@ -16,10 +24,14 @@ export function getStoredKey(): string | null {
|
|||
}
|
||||
|
||||
export function clearKey(): void {
|
||||
if (!isBrowser()) return;
|
||||
|
||||
sessionStorage.removeItem(ENCRYPTION_KEY_NAME);
|
||||
localStorage.removeItem(ENCRYPTION_KEY_NAME);
|
||||
}
|
||||
|
||||
export function isKeyPersistent(): boolean {
|
||||
if (!isBrowser()) return false;
|
||||
|
||||
return localStorage.getItem(ENCRYPTION_KEY_NAME) !== null;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue