import CryptoJS from 'crypto-js'; import { APP_CONFIG } from '@/config'; interface StorageEnvelope { value: T; expiresAt: number; } const encrypt = (value: unknown) => { return CryptoJS.AES.encrypt(JSON.stringify(value), APP_CONFIG.STORAGE_ENCRYPTION_KEY).toString(); }; const decrypt = (value: string): T | null => { try { const decrypted = CryptoJS.AES.decrypt(value, APP_CONFIG.STORAGE_ENCRYPTION_KEY) .toString(CryptoJS.enc.Utf8); return decrypted ? JSON.parse(decrypted) as T : null; } catch (error) { return null; } }; export const encryptedStorage = { set(key: string, value: T, expiresInSeconds = 0) { const envelope: StorageEnvelope = { value, expiresAt: expiresInSeconds > 0 ? Date.now() + expiresInSeconds * 1000 : 0 }; uni.setStorageSync(key, encrypt(envelope)); }, get(key: string): T | null { const encryptedValue = uni.getStorageSync(key); if (typeof encryptedValue !== 'string' || !encryptedValue) return null; const envelope = decrypt>(encryptedValue); if (!envelope || typeof envelope !== 'object' || !('value' in envelope)) { uni.removeStorageSync(key); return null; } if (envelope.expiresAt > 0 && envelope.expiresAt <= Date.now()) { uni.removeStorageSync(key); return null; } return envelope.value; }, remove(key: string) { uni.removeStorageSync(key); } }; export const authStorage = { getToken() { return encryptedStorage.get(APP_CONFIG.STORAGE_TOKEN_KEY) || ''; }, setToken(token: string, expiresInSeconds = 0) { encryptedStorage.set(APP_CONFIG.STORAGE_TOKEN_KEY, token, expiresInSeconds); }, clearToken() { encryptedStorage.remove(APP_CONFIG.STORAGE_TOKEN_KEY); } };