feat: новая функция

This commit is contained in:
2025-10-08 18:01:14 +03:00
parent 2c53bce32a
commit 725e7fd5a2
60 changed files with 5427 additions and 3921 deletions

View File

@@ -10,12 +10,6 @@
* GitHub: https://github.com/HB3-ACCELERATOR
*/
// Роли пользователей
const USER_ROLES = {
USER: 1,
ADMIN: 2,
};
// Типы идентификаторов
const IDENTITY_TYPES = {
WALLET: 'wallet',
@@ -30,13 +24,6 @@ const MESSAGE_CHANNELS = {
EMAIL: 'email',
};
// Типы отправителей сообщений
const SENDER_TYPES = {
USER: 'user',
AI: 'ai',
ADMIN: 'admin',
};
// Коды ошибок
const ERROR_CODES = {
UNAUTHORIZED: 'unauthorized',
@@ -59,12 +46,27 @@ const API_CONFIG = {
TIMEOUT: 30000, // 30 секунд
};
// Новые константы для ИИ-ассистента (без admin)
const AI_USER_TYPES = {
REGULAR_USER: 'user',
EDITOR: 'editor',
READONLY: 'readonly'
};
const AI_SENDER_TYPES = {
USER: 'user',
EDITOR: 'editor',
READONLY: 'readonly',
ASSISTANT: 'assistant'
};
module.exports = {
USER_ROLES,
IDENTITY_TYPES,
MESSAGE_CHANNELS,
SENDER_TYPES,
ERROR_CODES,
SESSION_CONFIG,
API_CONFIG,
// Константы для ИИ-ассистента
AI_USER_TYPES,
AI_SENDER_TYPES,
};

View File

@@ -0,0 +1,89 @@
/**
* Copyright (c) 2024-2025 Тарабанов Александр Викторович
* All rights reserved.
*
* This software is proprietary and confidential.
* Unauthorized copying, modification, or distribution is prohibited.
*
* For licensing inquiries: info@hb3-accelerator.com
* Website: https://hb3-accelerator.com
* GitHub: https://github.com/HB3-ACCELERATOR
*/
/**
* Утилиты для работы с шифрованием
* Предоставляет единую точку доступа к ключу шифрования
*/
const fs = require('fs');
const path = require('path');
const logger = require('./logger');
// Кэш ключа шифрования
let cachedKey = null;
/**
* Получить ключ шифрования из файла или переменной окружения
* @returns {string} Ключ шифрования
*/
function getEncryptionKey() {
// Если ключ уже закэширован, возвращаем его
if (cachedKey) {
return cachedKey;
}
// Сначала пробуем прочитать из файла (приоритет)
// В Docker контейнере путь /app/ssl/keys/full_db_encryption.key
// В локальной разработке ../../ssl/keys/full_db_encryption.key
const keyPath = fs.existsSync('/app/ssl/keys/full_db_encryption.key')
? '/app/ssl/keys/full_db_encryption.key'
: path.join(__dirname, '../../ssl/keys/full_db_encryption.key');
if (fs.existsSync(keyPath)) {
try {
cachedKey = fs.readFileSync(keyPath, 'utf8').trim();
logger.info('[EncryptionUtils] Ключ шифрования загружен из файла');
return cachedKey;
} catch (error) {
logger.error('[EncryptionUtils] Ошибка чтения ключа из файла:', error);
}
}
// Если файла нет, пробуем переменную окружения
if (process.env.ENCRYPTION_KEY) {
cachedKey = process.env.ENCRYPTION_KEY;
logger.info('[EncryptionUtils] Ключ шифрования загружен из переменной окружения');
return cachedKey;
}
// Если ничего не найдено, бросаем ошибку
logger.error('[EncryptionUtils] Ключ шифрования не найден ни в файле, ни в переменной окружения!');
throw new Error('Encryption key not found');
}
/**
* Проверить, включено ли шифрование
* @returns {boolean}
*/
function isEnabled() {
try {
getEncryptionKey();
return true;
} catch (error) {
return false;
}
}
/**
* Очистить кэш ключа (для тестов)
*/
function clearCache() {
cachedKey = null;
}
module.exports = {
getEncryptionKey,
isEnabled,
clearCache
};

View File

@@ -34,18 +34,8 @@ function generateVerificationCode(length = 6) {
// Проверка существования идентификатора пользователя
async function checkUserIdentity(userId, provider, providerId) {
// Получаем ключ шифрования
const fs = require('fs');
const path = require('path');
let encryptionKey = 'default-key';
try {
const keyPath = path.join(__dirname, '../ssl/keys/full_db_encryption.key');
if (fs.existsSync(keyPath)) {
encryptionKey = fs.readFileSync(keyPath, 'utf8').trim();
}
} catch (keyError) {
console.error('Error reading encryption key:', keyError);
}
const encryptionUtils = require('./encryptionUtils');
const encryptionKey = encryptionUtils.getEncryptionKey();
const result = await db.getQuery()(
'SELECT * FROM user_identities WHERE user_id = $1 AND provider_encrypted = encrypt_text($2, $4) AND provider_id_encrypted = encrypt_text($3, $4)',

View File

@@ -2,7 +2,7 @@ const winston = require('winston');
const path = require('path');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'warn', // Изменено с 'info' на 'warn'
level: process.env.LOG_LEVEL || 'info', // Уровень по умолчанию 'info' для показа логов ботов
format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
transports: [
new winston.transports.Console({