UNPKG

sui-svelte-wallet-kit

Version:

Svelte 5 wallet kit for Sui: connect wallets, manage accounts, SuiNS, balance, sign transactions/messages

101 lines (100 loc) 3.28 kB
/** * CredentialStorage * Handles persistence of passkey credentials */ const STORAGE_KEY = 'sui-passkey-credentials'; const STORAGE_VERSION = 1; /** * Default localStorage implementation of CredentialStorage */ export class LocalStorageCredentialStorage { key; constructor(key = STORAGE_KEY) { this.key = key; } async get() { if (typeof localStorage === 'undefined') return null; try { const data = localStorage.getItem(this.key); if (!data) return null; const parsed = JSON.parse(data); // Validate version if (parsed.version !== STORAGE_VERSION) { // Handle migration if needed in the future console.warn(`Credential storage version mismatch: ${parsed.version} vs ${STORAGE_VERSION}`); } return parsed; } catch (error) { console.error('Failed to read credentials from storage:', error); return null; } } async set(credentials) { if (typeof localStorage === 'undefined') { throw new Error('localStorage is not available'); } try { localStorage.setItem(this.key, JSON.stringify(credentials)); } catch (error) { console.error('Failed to save credentials to storage:', error); throw error; } } async clear() { if (typeof localStorage === 'undefined') return; try { localStorage.removeItem(this.key); } catch (error) { console.error('Failed to clear credentials from storage:', error); } } } /** * Helper functions for credential management */ export function createEmptyStorage() { return { credentials: [], version: STORAGE_VERSION }; } export function addCredential(storage, credential) { // Check if credential already exists const existingIndex = storage.credentials.findIndex((c) => c.credentialId === credential.credentialId); if (existingIndex >= 0) { // Update existing credential const updated = [...storage.credentials]; updated[existingIndex] = { ...credential, lastUsedAt: Date.now() }; return { ...storage, credentials: updated }; } // Add new credential return { ...storage, credentials: [...storage.credentials, credential] }; } export function findCredentialByAddress(storage, address) { return storage.credentials.find((c) => c.suiAddress === address); } export function findCredentialById(storage, credentialId) { return storage.credentials.find((c) => c.credentialId === credentialId); } export function findCredentialsByRpId(storage, rpId) { return storage.credentials.filter((c) => c.rpId === rpId); } export function removeCredential(storage, credentialId) { return { ...storage, credentials: storage.credentials.filter((c) => c.credentialId !== credentialId) }; } export function updateLastUsed(storage, credentialId) { const updated = storage.credentials.map((c) => c.credentialId === credentialId ? { ...c, lastUsedAt: Date.now() } : c); return { ...storage, credentials: updated }; }