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

191 lines
6.2 KiB
TypeScript

/**
* Cryptographic utilities for encryption, hashing, and secure random generation.
* Uses AES-256-GCM for reversible encryption and SHA-256 for one-way indexes.
*/
import * as crypto from '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: string | undefined, label: string): Buffer | null {
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(): Buffer[] {
const keys: Buffer[] = [];
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(): Buffer {
return getEncryptionKeys()[0];
}
function decryptWithKey(ciphertext: string, key: Buffer): string {
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(): Buffer {
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
*/
export function encrypt(plaintext: string): string {
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
*/
export function decrypt(ciphertext: string): string {
const keys = getEncryptionKeys();
let lastError: Error | null = 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. */
export function isEncryptedWithCurrentKey(ciphertext: string): boolean {
try {
decryptWithKey(ciphertext, getPrimaryKey());
return true;
} catch {
return false;
}
}
/** Re-encrypts a value produced by encrypt() with the current key. */
export function reencrypt(ciphertext: string): string {
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
*/
export function hashForIndex(value: string): string {
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
*/
export function hashForPhone(phone: string): string {
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
*/
export function hashToken(token: string): string {
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
*/
export function randomHex(bytes: number = 32): string {
return crypto.randomBytes(bytes).toString('hex');
}
const SENSITIVE_PREFIX = 'enc:v1:';
/**
* Encrypts a sensitive value for database storage (prefix marks ciphertext version).
*/
export function encryptSensitive(plaintext: string): string {
if (!plaintext) return '';
return `${SENSITIVE_PREFIX}${encrypt(plaintext)}`;
}
/**
* Decrypts a value stored by encryptSensitive; returns legacy plaintext as-is.
*/
export function decryptSensitive(stored: string | null | undefined): string {
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. */
export function reencryptSensitive(stored: string | null | undefined): string | null {
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. */
export function encryptJson(data: unknown): string {
return encryptSensitive(JSON.stringify(data));
}
/** Decrypts JSON stored via encryptJson. */
export function decryptJson<T>(stored: string | null | undefined): T | null {
if (!stored) return null;
try {
return JSON.parse(decryptSensitive(stored)) as T;
} catch {
return null;
}
}