Files
iistwin/server/crypto.ts
Ильяс Султанов 1f5ecb6da4 fix(number-fields): избегаем потери точности длинных чисел
- number-поля теперь рендерятся как text + inputMode=numeric,
  чтобы браузер не округлял значения через input type=number
- пробелы при вставке в number-поля удаляются
- бэкенд нормализует значения number-полей в строку перед сохранением
- добавлен хелпер normalizeFieldValueForStorage

Closes: искажение расчётного счёта и других длинных числовых полей
2026-07-07 21:03:40 +03:00

82 lines
2.5 KiB
TypeScript

import crypto from 'crypto';
const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16;
const SALT_LENGTH = 16;
const AUTH_TAG_LENGTH = 16;
const KEY_LENGTH = 32;
function deriveKey(secret: string, salt: Buffer): Buffer {
return crypto.scryptSync(secret, salt, KEY_LENGTH);
}
function getSecret(): string {
const secret = process.env.SESSION_SECRET;
if (!secret) {
throw new Error('SESSION_SECRET environment variable is required for encryption');
}
return secret;
}
export function encrypt(text: string): string {
if (!text) return text;
const secret = getSecret();
const salt = crypto.randomBytes(SALT_LENGTH);
const key = deriveKey(secret, salt);
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
// Format: salt:iv:authTag:ciphertext (4 parts — v2)
return `${salt.toString('hex')}:${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
}
export function decrypt(encryptedText: string): string {
if (!encryptedText || !encryptedText.includes(':')) return encryptedText;
try {
const secret = getSecret();
const parts = encryptedText.split(':');
if (parts.length === 4) {
// v2 format: salt:iv:authTag:ciphertext
const salt = Buffer.from(parts[0], 'hex');
const iv = Buffer.from(parts[1], 'hex');
const authTag = Buffer.from(parts[2], 'hex');
const encrypted = parts[3];
const key = deriveKey(secret, salt);
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
if (parts.length === 3) {
// v1 format: iv:authTag:ciphertext (fixed salt 'salt')
const key = crypto.scryptSync(secret, 'salt', KEY_LENGTH);
const iv = Buffer.from(parts[0], 'hex');
const authTag = Buffer.from(parts[1], 'hex');
const encrypted = parts[2];
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
return encryptedText;
} catch (error) {
console.error('Decryption failed:', error);
return encryptedText;
}
}