"use strict"; /** * Cryptographic utilities for encryption, hashing, and secure random generation. * Uses AES-256-GCM for reversible encryption and SHA-256 for one-way indexes. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.encrypt = encrypt; exports.decrypt = decrypt; exports.hashForIndex = hashForIndex; exports.hashForPhone = hashForPhone; exports.hashToken = hashToken; exports.randomHex = randomHex; exports.encryptSensitive = encryptSensitive; exports.decryptSensitive = decryptSensitive; exports.encryptJson = encryptJson; exports.decryptJson = decryptJson; const crypto = __importStar(require("crypto")); const ALGORITHM = 'aes-256-gcm'; const IV_LENGTH = 16; const AUTH_TAG_LENGTH = 16; const SALT_LENGTH = 32; const KEY_LENGTH = 32; /** * Loads and validates the ENCRYPTION_KEY from the environment as a 32-byte buffer. * @returns AES-256 key buffer * @throws When ENCRYPTION_KEY is missing or not a 64-character hex string */ function getKey() { const keyHex = process.env.ENCRYPTION_KEY; if (!keyHex || keyHex.length !== 64 || !/^[0-9a-fA-F]+$/.test(keyHex)) { throw new Error('ENCRYPTION_KEY must be 32-byte hex string (64 chars)'); } return Buffer.from(keyHex, 'hex'); } /** * Encrypts plaintext with AES-256-GCM using a random IV and auth tag. * @param plaintext UTF-8 string to encrypt * @returns Base64 payload containing IV, auth tag, and ciphertext */ function encrypt(plaintext) { const key = getKey(); const iv = crypto.randomBytes(IV_LENGTH); const cipher = crypto.createCipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH }); const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]); const authTag = cipher.getAuthTag(); return Buffer.concat([iv, authTag, encrypted]).toString('base64'); } /** * Decrypts a payload produced by encrypt(). * @param ciphertext Base64 string with IV, auth tag, and ciphertext * @returns Original UTF-8 plaintext * @throws When the auth tag is invalid or the key does not match */ function decrypt(ciphertext) { const key = getKey(); const buf = Buffer.from(ciphertext, 'base64'); const iv = buf.subarray(0, IV_LENGTH); const authTag = buf.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH); const encrypted = buf.subarray(IV_LENGTH + AUTH_TAG_LENGTH); const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH }); decipher.setAuthTag(authTag); return decipher.update(encrypted) + decipher.final('utf8'); } /** * Produces a SHA-256 hash of a normalized string for database uniqueness indexes. * @param value Raw value; lowercased and trimmed before hashing * @returns Hex-encoded SHA-256 digest */ function hashForIndex(value) { return crypto.createHash('sha256').update(value.toLowerCase().trim()).digest('hex'); } /** * Normalizes a phone number to digits only, then hashes for uniqueness index. * @param phone Phone string with optional formatting characters * @returns Hex-encoded SHA-256 digest of digit-only form */ function hashForPhone(phone) { const digits = phone.replace(/\D/g, ''); return crypto.createHash('sha256').update(digits).digest('hex'); } /** * Hashes a token (e.g. refresh token) for secure storage without reversible encryption. * @param token Raw token string * @returns Hex-encoded SHA-256 digest */ function hashToken(token) { return crypto.createHash('sha256').update(token).digest('hex'); } /** * Generates cryptographically secure random bytes as a hex string. * @param bytes Number of random bytes (default 32) * @returns Hex-encoded random string */ function randomHex(bytes = 32) { return crypto.randomBytes(bytes).toString('hex'); } const SENSITIVE_PREFIX = 'enc:v1:'; /** * Encrypts a sensitive value for database storage (prefix marks ciphertext version). */ function encryptSensitive(plaintext) { if (!plaintext) return ''; return `${SENSITIVE_PREFIX}${encrypt(plaintext)}`; } /** * Decrypts a value stored by encryptSensitive; returns legacy plaintext as-is. */ function decryptSensitive(stored) { if (!stored) return ''; if (stored.startsWith(SENSITIVE_PREFIX)) { return decrypt(stored.slice(SENSITIVE_PREFIX.length)); } return stored; } /** Encrypts a JSON-serializable object for database storage. */ function encryptJson(data) { return encryptSensitive(JSON.stringify(data)); } /** Decrypts JSON stored via encryptJson. */ function decryptJson(stored) { if (!stored) return null; try { return JSON.parse(decryptSensitive(stored)); } catch { return null; } } //# sourceMappingURL=crypto.js.map