All files / src/lib secure-storage.ts

34.17% Statements 95/278
67.85% Branches 19/28
40.9% Functions 9/22
34.17% Lines 95/278

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 4951x                                             1x     1x 1x     1x         23x 23x 23x 23x                             23x           1x           1x 11x   11x                               11x 11x             1x 11x                           11x 11x           1x 1x                 1x 1x         1x     1x                   17x 17x 16x 16x   1x   1x 1x 1x 1x   1x 1x 1x         7x 7x 7x 7x 7x     7x         11x 11x 11x   11x 1x   1x 1x 1x   10x 10x 10x 10x   10x 11x         11x     11x           11x 11x   11x 11x   11x 7x 7x 7x 7x 7x 1x   1x 7x     5x 11x 2x 2x   3x 11x     11x         1x 1x 1x 1x 1x     1x                                                     1x         1x               1x               1x     1x             1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                          
/**
 * ZCLAW Secure Storage
 *
 * Provides secure credential storage using the OS keyring/keychain.
 * Falls back to encrypted localStorage when not running in Tauri or if keyring is unavailable.
 *
 * Platform support:
 * - Windows: DPAPI
 * - macOS: Keychain
 * - Linux: Secret Service API (gnome-keyring, kwallet, etc.)
 * - Fallback: AES-GCM encrypted localStorage
 */
 
import { invoke } from '@tauri-apps/api/core';
import { isTauriRuntime } from './tauri-gateway';
import {
  deriveKey,
  encrypt,
  decrypt,
  generateMasterKey,
} from './crypto-utils';
 
// Cache for keyring availability check
let keyringAvailable: boolean | null = null;
 
// Encryption constants for localStorage fallback
const ENCRYPTED_PREFIX = 'enc_';
const MASTER_KEY_NAME = 'zclaw-master-key';
 
// Cache for the derived crypto key
let cachedCryptoKey: CryptoKey | null = null;
 
/**
 * Check if secure storage (keyring) is available
 */
export async function isSecureStorageAvailable(): Promise<boolean> {
  if (!isTauriRuntime()) {
    return false;
  }
 
  // Use cached result if available
  if (keyringAvailable !== null) {
    return keyringAvailable;
  }
 
  try {
    keyringAvailable = await invoke<boolean>('secure_store_is_available');
    return keyringAvailable;
  } catch (error) {
    console.warn('[SecureStorage] Keyring not available:', error);
    keyringAvailable = false;
    return false;
  }
}
 
/**
 * Secure storage interface
 * Uses OS keyring when available, falls back to encrypted localStorage
 */
export const secureStorage = {
  /**
   * Store a value securely
   * @param key - Storage key
   * @param value - Value to store
   */
  async set(key: string, value: string): Promise<void> {
    const trimmedValue = value.trim();
 
    if (await isSecureStorageAvailable()) {
      try {
        if (trimmedValue) {
          await invoke('secure_store_set', { key, value: trimmedValue });
        } else {
          await invoke('secure_store_delete', { key });
        }
        // Also write encrypted backup to localStorage for migration support
        await writeEncryptedLocalStorage(key, trimmedValue);
        return;
      } catch (error) {
        console.warn('[SecureStorage] Failed to use keyring, falling back to encrypted localStorage:', error);
      }
    }
 
    // Fallback to encrypted localStorage
    await writeEncryptedLocalStorage(key, trimmedValue);
  },
 
  /**
   * Retrieve a value from secure storage
   * @param key - Storage key
   * @returns Stored value or null if not found
   */
  async get(key: string): Promise<string | null> {
    if (await isSecureStorageAvailable()) {
      try {
        const value = await invoke<string>('secure_store_get', { key });
        if (value !== null && value !== undefined && value !== '') {
          return value;
        }
        // If keyring returned empty, try encrypted localStorage fallback for migration
        return await readEncryptedLocalStorage(key);
      } catch (error) {
        console.warn('[SecureStorage] Failed to read from keyring, trying encrypted localStorage:', error);
      }
    }
 
    // Fallback to encrypted localStorage
    return await readEncryptedLocalStorage(key);
  },
 
  /**
   * Delete a value from secure storage
   * @param key - Storage key
   */
  async delete(key: string): Promise<void> {
    if (await isSecureStorageAvailable()) {
      try {
        await invoke('secure_store_delete', { key });
      } catch (error) {
        console.warn('[SecureStorage] Failed to delete from keyring:', error);
      }
    }
 
    // Always clear localStorage backup
    clearLocalStorageBackup(key);
  },
 
  /**
   * Check if secure storage is being used (vs localStorage fallback)
   */
  async isUsingKeyring(): Promise<boolean> {
    return isSecureStorageAvailable();
  },
};
 
/**
 * localStorage backup functions for migration and fallback
 * Now with AES-GCM encryption for non-Tauri environments
 */
 
/**
 * Get or create the master encryption key for localStorage fallback
 */
async function getOrCreateMasterKey(): Promise<CryptoKey> {
  if (cachedCryptoKey) {
    return cachedCryptoKey;
  }
 
  let masterKeyRaw = localStorage.getItem(MASTER_KEY_NAME);
 
  if (!masterKeyRaw) {
    masterKeyRaw = generateMasterKey();
    localStorage.setItem(MASTER_KEY_NAME, masterKeyRaw);
  }
 
  cachedCryptoKey = await deriveKey(masterKeyRaw);
  return cachedCryptoKey;
}
 
/**
 * Check if a stored value is encrypted (has iv and data fields)
 */
function isEncrypted(value: string): boolean {
  try {
    const parsed = JSON.parse(value);
    return parsed && typeof parsed.iv === 'string' && typeof parsed.data === 'string';
  } catch {
    return false;
  }
}
 
/**
 * Write encrypted data to localStorage
 */
async function writeEncryptedLocalStorage(key: string, value: string): Promise<void> {
  try {
    const encryptedKey = ENCRYPTED_PREFIX + key;
 
    if (!value) {
      localStorage.removeItem(encryptedKey);
      // Also remove legacy unencrypted key
      localStorage.removeItem(key);
      return;
    }
 
    try {
      const cryptoKey = await getOrCreateMasterKey();
      const encrypted = await encrypt(value, cryptoKey);
      localStorage.setItem(encryptedKey, JSON.stringify(encrypted));
      // Remove legacy unencrypted key if it exists
      localStorage.removeItem(key);
    } catch (error) {
      console.error('[SecureStorage] Encryption failed:', error);
      // Fallback to plaintext if encryption fails (should not happen)
      localStorage.setItem(key, value);
    }
  } catch {
    // Ignore localStorage failures
  }
}
 
/**
 * Read and decrypt data from localStorage
 * Supports both encrypted and legacy unencrypted formats
 */
async function readEncryptedLocalStorage(key: string): Promise<string | null> {
  try {
    // Try encrypted key first
    const encryptedKey = ENCRYPTED_PREFIX + key;
    const encryptedRaw = localStorage.getItem(encryptedKey);
 
    if (encryptedRaw && isEncrypted(encryptedRaw)) {
      try {
        const cryptoKey = await getOrCreateMasterKey();
        const encrypted = JSON.parse(encryptedRaw);
        return await decrypt(encrypted, cryptoKey);
      } catch (error) {
        console.error('[SecureStorage] Decryption failed:', error);
        // Fall through to try legacy key
      }
    }
 
    // Try legacy unencrypted key for backward compatibility
    const legacyValue = localStorage.getItem(key);
    if (legacyValue !== null) {
      return legacyValue;
    }
 
    return null;
  } catch {
    return null;
  }
}
 
/**
 * Clear data from localStorage (both encrypted and legacy)
 */
function clearLocalStorageBackup(key: string): void {
  try {
    localStorage.removeItem(ENCRYPTED_PREFIX + key);
    localStorage.removeItem(key);
  } catch {
    // Ignore localStorage failures
  }
}
 
// Keep synchronous versions for backward compatibility (deprecated)
function writeLocalStorageBackup(key: string, value: string): void {
  try {
    if (value) {
      localStorage.setItem(key, value);
    } else {
      localStorage.removeItem(key);
    }
  } catch {
    // Ignore localStorage failures
  }
}
 
function readLocalStorageBackup(key: string): string | null {
  try {
    return localStorage.getItem(key);
  } catch {
    return null;
  }
}
 
/**
 * Synchronous versions for compatibility with existing code
 * These use localStorage only and are provided for gradual migration
 */
export const secureStorageSync = {
  /**
   * Synchronously get a value from localStorage (for migration only)
   * @deprecated Use async secureStorage.get() instead
   */
  get(key: string): string | null {
    return readLocalStorageBackup(key);
  },
 
  /**
   * Synchronously set a value in localStorage (for migration only)
   * @deprecated Use async secureStorage.set() instead
   */
  set(key: string, value: string): void {
    writeLocalStorageBackup(key, value);
  },
 
  /**
   * Synchronously delete a value from localStorage (for migration only)
   * @deprecated Use async secureStorage.delete() instead
   */
  delete(key: string): void {
    clearLocalStorageBackup(key);
  },
};
 
// === Device Keys Secure Storage ===
 
/**
 * Storage keys for Ed25519 device keys
 */
const DEVICE_KEYS_PRIVATE_KEY = 'zclaw_device_keys_private';
const DEVICE_KEYS_PUBLIC_KEY = 'zclaw_device_keys_public';
const DEVICE_KEYS_CREATED = 'zclaw_device_keys_created';
const DEVICE_KEYS_LEGACY = 'zclaw_device_keys'; // Old format for migration
 
/**
 * Ed25519 SignKeyPair interface (compatible with tweetnacl)
 */
export interface Ed25519KeyPair {
  publicKey: Uint8Array;
  secretKey: Uint8Array;
}
 
/**
 * Legacy device keys format (stored in localStorage)
 * Used for migration from the old format.
 */
interface LegacyDeviceKeys {
  deviceId: string;
  publicKeyBase64: string;
  secretKeyBase64: string;
}
 
/**
 * Base64 URL-safe encode (without padding)
 */
function base64UrlEncode(bytes: Uint8Array): string {
  let binary = '';
  for (let i = 0; i < bytes.length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
 
/**
 * Base64 URL-safe decode
 */
function base64UrlDecode(str: string): Uint8Array {
  str = str.replace(/-/g, '+').replace(/_/g, '/');
  while (str.length % 4) str += '=';
  const binary = atob(str);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return bytes;
}
 
/**
 * Store device keys securely.
 * The secret key is stored in the OS keyring when available,
 * falling back to localStorage with a warning.
 *
 * @param publicKey - Ed25519 public key (32 bytes)
 * @param secretKey - Ed25519 secret key (64 bytes)
 */
export async function storeDeviceKeys(
  publicKey: Uint8Array,
  secretKey: Uint8Array
): Promise<void> {
  const publicKeyBase64 = base64UrlEncode(publicKey);
  const secretKeyBase64 = base64UrlEncode(secretKey);
  const createdAt = Date.now().toString();
 
  if (await isSecureStorageAvailable()) {
    // Store secret key in keyring (most secure)
    await secureStorage.set(DEVICE_KEYS_PRIVATE_KEY, secretKeyBase64);
    // Public key and metadata can go to localStorage (non-sensitive)
    localStorage.setItem(DEVICE_KEYS_PUBLIC_KEY, publicKeyBase64);
    localStorage.setItem(DEVICE_KEYS_CREATED, createdAt);
    // Clear legacy format if present
    try {
      localStorage.removeItem(DEVICE_KEYS_LEGACY);
    } catch {
      // Ignore
    }
  } else {
    // Fallback: store in localStorage (less secure, but better than nothing)
    console.warn(
      '[SecureStorage] Keyring not available, using localStorage fallback for device keys. ' +
        'Consider running in Tauri for secure key storage.'
    );
    localStorage.setItem(
      DEVICE_KEYS_LEGACY,
      JSON.stringify({
        publicKeyBase64,
        secretKeyBase64,
        createdAt,
      })
    );
  }
}
 
/**
 * Retrieve device keys from secure storage.
 * Attempts to read from keyring first, then falls back to localStorage.
 * Also handles migration from the legacy format.
 *
 * @returns Key pair or null if not found
 */
export async function getDeviceKeys(): Promise<Ed25519KeyPair | null> {
  // Try keyring storage first (new format)
  if (await isSecureStorageAvailable()) {
    const secretKeyBase64 = await secureStorage.get(DEVICE_KEYS_PRIVATE_KEY);
    const publicKeyBase64 = localStorage.getItem(DEVICE_KEYS_PUBLIC_KEY);
 
    if (secretKeyBase64 && publicKeyBase64) {
      try {
        return {
          publicKey: base64UrlDecode(publicKeyBase64),
          secretKey: base64UrlDecode(secretKeyBase64),
        };
      } catch (e) {
        console.warn('[SecureStorage] Failed to decode keys from keyring:', e);
      }
    }
  }
 
  // Try legacy format (localStorage)
  const legacyStored = localStorage.getItem(DEVICE_KEYS_LEGACY);
  if (legacyStored) {
    try {
      const parsed: LegacyDeviceKeys = JSON.parse(legacyStored);
      return {
        publicKey: base64UrlDecode(parsed.publicKeyBase64),
        secretKey: base64UrlDecode(parsed.secretKeyBase64),
      };
    } catch (e) {
      console.warn('[SecureStorage] Failed to decode legacy keys:', e);
    }
  }
 
  return null;
}
 
/**
 * Delete device keys from all storage locations.
 * Used when keys need to be regenerated.
 */
export async function deleteDeviceKeys(): Promise<void> {
  // Delete from keyring
  if (await isSecureStorageAvailable()) {
    await secureStorage.delete(DEVICE_KEYS_PRIVATE_KEY);
  }
 
  // Delete from localStorage
  try {
    localStorage.removeItem(DEVICE_KEYS_PUBLIC_KEY);
    localStorage.removeItem(DEVICE_KEYS_CREATED);
    localStorage.removeItem(DEVICE_KEYS_LEGACY);
  } catch {
    // Ignore localStorage errors
  }
}
 
/**
 * Check if device keys exist in any storage.
 */
export async function hasDeviceKeys(): Promise<boolean> {
  const keys = await getDeviceKeys();
  return keys !== null;
}
 
/**
 * Get the creation timestamp of stored device keys.
 * Returns null if keys don't exist or timestamp is unavailable.
 */
export async function getDeviceKeysCreatedAt(): Promise<number | null> {
  // Try new format
  const created = localStorage.getItem(DEVICE_KEYS_CREATED);
  if (created) {
    const parsed = parseInt(created, 10);
    if (!isNaN(parsed)) {
      return parsed;
    }
  }
 
  // Try legacy format
  const legacyStored = localStorage.getItem(DEVICE_KEYS_LEGACY);
  if (legacyStored) {
    try {
      const parsed = JSON.parse(legacyStored);
      if (typeof parsed.createdAt === 'number' || typeof parsed.createdAt === 'string') {
        return parseInt(String(parsed.createdAt), 10);
      }
    } catch {
      // Ignore
    }
  }
 
  return null;
}