wip library to store cold objects in s3, warm objects on disk, and hot objects in memory
nodejs typescript
at main 1.6 kB view raw
1import { createHash, timingSafeEqual } from 'node:crypto'; 2 3/** 4 * Calculate SHA256 checksum of data. 5 * 6 * @param data - Data to checksum 7 * @returns Hex-encoded SHA256 hash 8 * 9 * @remarks 10 * Used for data integrity verification. The checksum is stored in metadata 11 * and can be used to detect corruption or tampering. 12 * 13 * @example 14 * ```typescript 15 * const data = new TextEncoder().encode('Hello, world!'); 16 * const checksum = calculateChecksum(data); 17 * console.log(checksum); // '315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3' 18 * ``` 19 */ 20export function calculateChecksum(data: Uint8Array): string { 21 const hash = createHash('sha256'); 22 hash.update(data); 23 return hash.digest('hex'); 24} 25 26/** 27 * Verify that data matches an expected checksum. 28 * 29 * @param data - Data to verify 30 * @param expectedChecksum - Expected SHA256 checksum (hex-encoded) 31 * @returns true if checksums match, false otherwise 32 * 33 * @remarks 34 * Uses constant-time comparison to prevent timing attacks. 35 * 36 * @example 37 * ```typescript 38 * const isValid = verifyChecksum(data, metadata.checksum); 39 * if (!isValid) { 40 * throw new Error('Data corruption detected'); 41 * } 42 * ``` 43 */ 44export function verifyChecksum(data: Uint8Array, expectedChecksum: string): boolean { 45 const actualChecksum = calculateChecksum(data); 46 47 // Use constant-time comparison to prevent timing attacks 48 try { 49 return timingSafeEqual( 50 Buffer.from(actualChecksum, 'hex'), 51 Buffer.from(expectedChecksum, 'hex') 52 ); 53 } catch { 54 // If checksums have different lengths, timingSafeEqual throws 55 return false; 56 } 57}