All files / src/lib crypto-utils.ts

82.87% Statements 150/181
97.29% Branches 36/37
68.42% Functions 13/19
82.87% Lines 150/181

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                        1x 1x 1x         1x 61x   59x 61x 1468x 1468x 59x 59x         1x 31x   29x 29x 31x 630x 630x 28x 28x                         1x         13x 13x 13x 16x     16x 13x         13x 13x 13x 13x 13x 13x 13x                   13x 13x 13x 13x   13x     13x 13x 13x 8x 8x   5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x     5x   5x 5x                             1x                 18x 18x 18x 18x 18x 18x   18x 18x 18x 18x 18x   18x 18x 18x 18x 18x 18x                 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x   12x 12x               1x 8x 8x 8x               1x                     1x 3x 1x 1x   2x 3x 8x 8x   2x 2x               2x 2x 2x 2x 2x     2x 2x 2x 2x                                                 1x                         1x                     1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x                 1x               1x                     1x 5x 1x 1x   4x 4x 4x 2x 1x 1x   5x  
/**
 * Cryptographic utilities for secure storage
 * Uses Web Crypto API for AES-GCM encryption
 *
 * Security features:
 * - AES-256-GCM for authenticated encryption
 * - PBKDF2 with 100,000 iterations for key derivation
 * - Random IV for each encryption operation
 * - Constant-time comparison for integrity verification
 * - Secure key caching with automatic expiration
 */
 
const SALT = new TextEncoder().encode('zclaw-secure-storage-salt');
const ITERATIONS = 100000;
const KEY_EXPIRY_MS = 30 * 60 * 1000; // 30 minutes
 
/**
 * Convert Uint8Array to base64 string
 */
export function arrayToBase64(array: Uint8Array): string {
  if (array.length === 0) return '';
 
  let binary = '';
  for (let i = 0; i < array.length; i++) {
    binary += String.fromCharCode(array[i]);
  }
  return btoa(binary);
}
 
/**
 * Convert base64 string to Uint8Array
 */
export function base64ToArray(base64: string): Uint8Array {
  if (!base64) return new Uint8Array([]);
 
  const binary = atob(base64);
  const array = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    array[i] = binary.charCodeAt(i);
  }
  return array;
}
 
/**
 * Key cache entry with expiration
 */
interface CachedKey {
  key: CryptoKey;
  createdAt: number;
}
 
/**
 * Cache for derived keys with automatic expiration
 */
const keyCache = new Map<string, CachedKey>();
 
/**
 * Clean up expired keys from cache
 */
function cleanupExpiredKeys(): void {
  const now = Date.now();
  for (const [cacheKey, entry] of keyCache.entries()) {
    if (now - entry.createdAt > KEY_EXPIRY_MS) {
      keyCache.delete(cacheKey);
    }
  }
}
 
/**
 * Generate a cache key from master key and salt
 */
function getCacheKey(masterKey: string, salt: Uint8Array): string {
  const encoder = new TextEncoder();
  const combined = new Uint8Array(encoder.encode(masterKey).length + salt.length);
  combined.set(encoder.encode(masterKey), 0);
  combined.set(salt, encoder.encode(masterKey).length);
  return arrayToBase64(combined.slice(0, 32)); // Use first 32 bytes as cache key
}
 
/**
 * Derive an encryption key from a master key
 * Uses PBKDF2 with SHA-256 for key derivation
 *
 * @param masterKey - The master key string
 * @param salt - Optional salt (uses default if not provided)
 * @returns Promise<CryptoKey> - The derived encryption key
 */
export async function deriveKey(
  masterKey: string,
  salt: Uint8Array = SALT
): Promise<CryptoKey> {
  // Clean up expired keys periodically
  cleanupExpiredKeys();
 
  // Check cache first
  const cacheKey = getCacheKey(masterKey, salt);
  const cached = keyCache.get(cacheKey);
  if (cached && Date.now() - cached.createdAt < KEY_EXPIRY_MS) {
    return cached.key;
  }
 
  const encoder = new TextEncoder();
  const keyMaterial = await crypto.subtle.importKey(
    'raw',
    encoder.encode(masterKey),
    'PBKDF2',
    false,
    ['deriveBits', 'deriveKey']
  );
 
  const derivedKey = await crypto.subtle.deriveKey(
    {
      name: 'PBKDF2',
      salt,
      iterations: ITERATIONS,
      hash: 'SHA-256',
    },
    keyMaterial,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt']
  );
 
  // Cache the derived key
  keyCache.set(cacheKey, { key: derivedKey, createdAt: Date.now() });
 
  return derivedKey;
}
 
/**
 * Encrypted data structure
 */
export interface EncryptedData {
  iv: string;
  data: string;
  authTag?: string; // For future use with separate auth tag
  version?: number; // Schema version for future migrations
}
 
/**
 * Current encryption schema version
 */
const ENCRYPTION_VERSION = 1;
 
/**
 * Encrypt data using AES-GCM
 *
 * @param plaintext - The plaintext string to encrypt
 * @param key - The encryption key
 * @returns Promise<EncryptedData> - The encrypted data with IV
 */
export async function encrypt(
  plaintext: string,
  key: CryptoKey
): Promise<EncryptedData> {
  const encoder = new TextEncoder();
  const iv = crypto.getRandomValues(new Uint8Array(12));
 
  const encrypted = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv },
    key,
    encoder.encode(plaintext)
  );
 
  return {
    iv: arrayToBase64(iv),
    data: arrayToBase64(new Uint8Array(encrypted)),
    version: ENCRYPTION_VERSION,
  };
}
 
/**
 * Decrypt data using AES-GCM
 *
 * @param encrypted - The encrypted data object
 * @param key - The decryption key
 * @returns Promise<string> - The decrypted plaintext
 */
export async function decrypt(
  encrypted: EncryptedData,
  key: CryptoKey
): Promise<string> {
  const decoder = new TextDecoder();
  const decrypted = await crypto.subtle.decrypt(
    { name: 'AES-GCM', iv: base64ToArray(encrypted.iv) },
    key,
    base64ToArray(encrypted.data)
  );
 
  return decoder.decode(decrypted);
}
 
/**
 * Generate a random master key for encryption
 * Uses cryptographically secure random number generator
 *
 * @returns string - Base64-encoded 256-bit random key
 */
export function generateMasterKey(): string {
  const array = crypto.getRandomValues(new Uint8Array(32));
  return arrayToBase64(array);
}
 
/**
 * Generate a random salt
 *
 * @param length - Salt length in bytes (default: 16)
 * @returns Uint8Array - Random salt
 */
export function generateSalt(length: number = 16): Uint8Array {
  return crypto.getRandomValues(new Uint8Array(length));
}
 
/**
 * Constant-time comparison to prevent timing attacks
 *
 * @param a - First byte array
 * @param b - Second byte array
 * @returns boolean - True if arrays are equal
 */
export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {
  if (a.length !== b.length) {
    return false;
  }
 
  let result = 0;
  for (let i = 0; i < a.length; i++) {
    result |= a[i] ^ b[i];
  }
 
  return result === 0;
}
 
/**
 * Hash a string using SHA-256
 *
 * @param input - The input string to hash
 * @returns Promise<string> - Hex-encoded hash
 */
export async function hashSha256(input: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(input);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const hashArray = new Uint8Array(hashBuffer);
 
  // Convert to hex string
  return Array.from(hashArray)
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}
 
/**
 * Hash a string using SHA-512 (for sensitive data)
 *
 * @param input - The input string to hash
 * @returns Promise<string> - Hex-encoded hash
 */
export async function hashSha512(input: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(input);
  const hashBuffer = await crypto.subtle.digest('SHA-512', data);
  const hashArray = new Uint8Array(hashBuffer);
 
  return Array.from(hashArray)
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}
 
/**
 * Generate a cryptographically secure random string
 *
 * @param length - Length of the string (default: 32)
 * @returns string - Random alphanumeric string
 */
export function generateRandomString(length: number = 32): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const array = crypto.getRandomValues(new Uint8Array(length));
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars[array[i] % chars.length];
  }
  return result;
}
 
/**
 * Clear the key cache (for logout or security events)
 */
export function clearKeyCache(): void {
  keyCache.clear();
}
 
/**
 * Encrypt a JSON object
 *
 * @param obj - The object to encrypt
 * @param key - The encryption key
 * @returns Promise<EncryptedData> - The encrypted data
 */
export async function encryptObject<T>(
  obj: T,
  key: CryptoKey
): Promise<EncryptedData> {
  const plaintext = JSON.stringify(obj);
  return encrypt(plaintext, key);
}
 
/**
 * Decrypt a JSON object
 *
 * @param encrypted - The encrypted data
 * @param key - The decryption key
 * @returns Promise<T> - The decrypted object
 */
export async function decryptObject<T>(
  encrypted: EncryptedData,
  key: CryptoKey
): Promise<T> {
  const plaintext = await decrypt(encrypted, key);
  return JSON.parse(plaintext) as T;
}
 
/**
 * Securely wipe a string from memory (best effort)
 * Note: JavaScript strings are immutable, so this only works for
 * data that was explicitly copied to a Uint8Array
 *
 * @param array - The byte array to wipe
 */
export function secureWipe(array: Uint8Array): void {
  crypto.getRandomValues(array);
  array.fill(0);
}
 
/**
 * Check if Web Crypto API is available
 */
export function isCryptoAvailable(): boolean {
  return (
    typeof crypto !== 'undefined' &&
    typeof crypto.subtle !== 'undefined' &&
    typeof crypto.getRandomValues === 'function'
  );
}
 
/**
 * Validate encrypted data structure
 */
export function isValidEncryptedData(data: unknown): data is EncryptedData {
  if (typeof data !== 'object' || data === null) {
    return false;
  }
 
  const obj = data as Record<string, unknown>;
  return (
    typeof obj.iv === 'string' &&
    typeof obj.data === 'string' &&
    obj.iv.length > 0 &&
    obj.data.length > 0
  );
}