games_app/backend/dist/utils/crypto.js
2026-07-07 15:03:17 +02:00

229 lines
7.9 KiB
JavaScript

"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.isEncryptedWithCurrentKey = isEncryptedWithCurrentKey;
exports.reencrypt = reencrypt;
exports.hashForIndex = hashForIndex;
exports.hashForPhone = hashForPhone;
exports.hashToken = hashToken;
exports.randomHex = randomHex;
exports.encryptSensitive = encryptSensitive;
exports.decryptSensitive = decryptSensitive;
exports.reencryptSensitive = reencryptSensitive;
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;
function parseKeyHex(keyHex, label) {
if (!keyHex)
return null;
if (keyHex.length !== 64 || !/^[0-9a-fA-F]+$/.test(keyHex)) {
throw new Error(`${label} must be a 32-byte hex string (64 chars)`);
}
return Buffer.from(keyHex, 'hex');
}
/**
* Returns encryption keys in priority order: current, then previous (for rotation).
*/
function getEncryptionKeys() {
const keys = [];
const current = parseKeyHex(process.env.ENCRYPTION_KEY, 'ENCRYPTION_KEY');
const previous = parseKeyHex(process.env.ENCRYPTION_KEY_PREVIOUS, 'ENCRYPTION_KEY_PREVIOUS');
if (current)
keys.push(current);
if (previous)
keys.push(previous);
if (!keys.length) {
throw new Error('ENCRYPTION_KEY must be 32-byte hex string (64 chars)');
}
return keys;
}
function getPrimaryKey() {
return getEncryptionKeys()[0];
}
function decryptWithKey(ciphertext, key) {
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');
}
/**
* 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() {
return getPrimaryKey();
}
/**
* 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 keys = getEncryptionKeys();
let lastError = null;
for (const key of keys) {
try {
return decryptWithKey(ciphertext, key);
}
catch (e) {
lastError = e instanceof Error ? e : new Error(String(e));
}
}
throw lastError ?? new Error('Decryption failed');
}
/** True when ciphertext was encrypted with the current ENCRYPTION_KEY. */
function isEncryptedWithCurrentKey(ciphertext) {
try {
decryptWithKey(ciphertext, getPrimaryKey());
return true;
}
catch {
return false;
}
}
/** Re-encrypts a value produced by encrypt() with the current key. */
function reencrypt(ciphertext) {
return encrypt(decrypt(ciphertext));
}
/**
* 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;
}
/** Re-encrypts a value stored via encryptSensitive with the current key. */
function reencryptSensitive(stored) {
if (!stored)
return null;
if (!stored.startsWith(SENSITIVE_PREFIX)) {
return encryptSensitive(stored);
}
const inner = stored.slice(SENSITIVE_PREFIX.length);
if (isEncryptedWithCurrentKey(inner))
return stored;
return encryptSensitive(decrypt(inner));
}
/** 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