UNPKG

@tradly/auth

Version:

Auth package for Tradly - handles authentication (email, phone, social login)

104 lines (103 loc) 3.1 kB
"use strict"; /** * Encryption utility for PK keys * Uses encoding with hash-based obfuscation for secure cookie storage * The PK key is encoded using Base64 with domain-based salt and hash verification */ Object.defineProperty(exports, "__esModule", { value: true }); exports.encryptPKKey = encryptPKKey; exports.decryptPKKey = decryptPKKey; /** * Generate a domain-based encryption key */ function generateKey(domain) { // Create a deterministic key from domain let key = 0; for (let i = 0; i < domain.length; i++) { key = (key << 5) - key + domain.charCodeAt(i); key = key & key; // Convert to 32-bit integer } return Math.abs(key).toString(36); } /** * Encode PK key with domain-based encryption * Uses Base64 encoding with salt and hash for security */ function encodePKKey(pkKey, domain) { // Create encryption key from domain const key = generateKey(domain); const salt = domain.split("").reverse().join(""); // Combine PK key with salt and key const combined = `${pkKey}:${salt}:${key}`; // Encode to Base64 const encoded = btoa(combined); // Add hash for integrity verification const hash = simpleHash(pkKey + domain + key); return `${encoded}.${hash}`; } /** * Decode PK key from encoded string */ function decodePKKey(encoded, domain) { try { const [encodedPart, hash] = encoded.split("."); if (!encodedPart || !hash) { return null; } // Decode from Base64 const decoded = atob(encodedPart); // Extract components const parts = decoded.split(":"); if (parts.length !== 3) { return null; } const [pkKey, salt, key] = parts; // Verify salt matches domain const expectedSalt = domain.split("").reverse().join(""); if (salt !== expectedSalt) { return null; } // Verify key matches domain const expectedKey = generateKey(domain); if (key !== expectedKey) { return null; } // Verify hash const expectedHash = simpleHash(pkKey + domain + key); if (hash !== expectedHash) { return null; // Hash mismatch - data may be corrupted or tampered } return pkKey; } catch (e) { console.warn("Failed to decode PK key:", e); return null; } } /** * Simple hash function for integrity checking * Uses a basic hash algorithm */ function simpleHash(str) { let hash = 0; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; // Convert to 32-bit integer } return Math.abs(hash).toString(36); } /** * Encrypt PK key for storage * Returns encoded string safe for cookie storage */ function encryptPKKey(pkKey, domain) { return encodePKKey(pkKey, domain); } /** * Decrypt PK key from storage * Returns original PK key or null if decryption fails */ function decryptPKKey(encoded, domain) { return decodePKKey(encoded, domain); }