Crypto
src/app/core/crypto/
Utilidades compartidas de cifrado simétrico para guardar secretos en MongoDB. Antes vivía solo dentro del módulo WhatsApp (session-encryption.ts); ahora lo usan WhatsApp y Meta.
secret-encryption.ts
- Algoritmo: AES-256-GCM, IV de 12 bytes aleatorio por cifrado.
- Clave: 32 bytes en base64 (
ENCRYPTION_KEY_LENGTH_BYTES = 32). Generar conopenssl rand -base64 32.
| Función | Descripción |
|---|---|
isValidEncryptionKey(raw) | true si raw decodifica a 32 bytes |
decodeEncryptionKey(raw, envName) | Devuelve el Buffer o lanza un error indicando la variable |
readEncryptionKey(envName) | Lee process.env[envName] y la decodifica |
encryptSecret(plaintext, key) | Devuelve EncryptedEnvelope { iv, tag, ciphertext } (todo en base64) |
decryptSecret(envelope, key) | Descifra; si la etiqueta GCM no valida lanza Failed to decrypt secret: authentication tag verification failed… |
isEncryptedEnvelope(value) | Type guard |
encrypted-envelope.model.ts
Subdocumento Mongoose EncryptedEnvelopeRecord (iv, tag, ciphertext; _id: false) y su EncryptedEnvelopeSchema, reutilizado en:
| Dónde | Campo | Clave (variable de entorno) |
|---|---|---|
WhatsappSession | creds | WHATSAPP_SESSION_ENCRYPTION_KEY |
WhatsappSessionKey | value | WHATSAPP_SESSION_ENCRYPTION_KEY |
Connection.metaConfig | accessToken (select: false) | META_TOKEN_ENCRYPTION_KEY |
Validación al arrancar
src/config/env.validation.ts exige ambas variables (WHATSAPP_SESSION_ENCRYPTION_KEY, META_TOKEN_ENCRYPTION_KEY) con formato válido y distintas entre sí; si no, la app no arranca con un mensaje que sugiere openssl rand -base64 32.