251128:1700 Backend to T3.1.1

This commit is contained in:
admin
2025-11-28 17:12:05 +07:00
parent b22d00877e
commit f7a43600a3
50 changed files with 4891 additions and 2849 deletions

View File

@@ -1,12 +1,13 @@
// File: src/common/services/crypto.service.ts
// บันทึกการแก้ไข: Encryption/Decryption Utility (T1.1)
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as crypto from 'crypto';
@Injectable()
export class CryptoService {
private readonly logger = new Logger(CryptoService.name);
private readonly algorithm = 'aes-256-cbc';
private readonly key: Buffer;
private readonly ivLength = 16;
@@ -19,22 +20,42 @@ export class CryptoService {
this.key = crypto.scryptSync(secret, 'salt', 32);
}
encrypt(text: string): string {
const iv = crypto.randomBytes(this.ivLength);
const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return `${iv.toString('hex')}:${encrypted}`;
encrypt(text: string | number | boolean): string {
if (text === null || text === undefined) return text as any;
try {
const stringValue = String(text);
const iv = crypto.randomBytes(this.ivLength);
const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
let encrypted = cipher.update(stringValue, 'utf8', 'hex');
encrypted += cipher.final('hex');
return `${iv.toString('hex')}:${encrypted}`;
} catch (error: any) {
// Fix TS18046: Cast error to any or Error to access .message
this.logger.error(`Encryption failed: ${error.message}`);
throw error;
}
}
decrypt(text: string): string {
const [ivHex, encryptedHex] = text.split(':');
if (!ivHex || !encryptedHex) return text;
if (!text || typeof text !== 'string' || !text.includes(':')) return text;
const iv = Buffer.from(ivHex, 'hex');
const decipher = crypto.createDecipheriv(this.algorithm, this.key, iv);
let decrypted = decipher.update(encryptedHex, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
try {
const [ivHex, encryptedHex] = text.split(':');
if (!ivHex || !encryptedHex) return text;
const iv = Buffer.from(ivHex, 'hex');
const decipher = crypto.createDecipheriv(this.algorithm, this.key, iv);
let decrypted = decipher.update(encryptedHex, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (error: any) {
// Fix TS18046: Cast error to any or Error to access .message
this.logger.warn(
`Decryption failed for value. Returning original text. Error: ${error.message}`,
);
// กรณี Decrypt ไม่ได้ ให้คืนค่าเดิมเพื่อป้องกัน App Crash
return text;
}
}
}