This commit is contained in:
Kirchik
2025-08-13 22:36:08 +02:00
parent 6d061248de
commit e23fc02f63
254 changed files with 9579 additions and 4378 deletions
+56
View File
@@ -399,6 +399,12 @@
font-style: normal;
}
.file-input-text.file-encrypted {
color: #27ae60;
font-weight: 500;
font-style: normal;
}
.file-input-wrapper::after {
content: "📎";
font-size: 1.1rem;
@@ -406,6 +412,56 @@
margin-left: 0.5rem;
}
.file-input-wrapper.file-encrypted::after {
content: "🔒";
color: #27ae60;
}
/* Индикатор процесса шифрования */
.encryption-status {
margin-top: 0.5rem;
padding: 0.5rem;
border-radius: 8px;
font-size: 0.9rem;
text-align: center;
transition: all 0.3s ease;
}
.encryption-status.encrypting {
background: #fff3cd;
color: #856404;
border: 1px solid #ffeaa7;
}
.encryption-status.encrypted {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.encryption-status.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
/* Анимация шифрования */
.encrypting-spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid #f3f3f3;
border-top: 2px solid #856404;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-right: 0.5rem;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.file-info {
margin-top: 0.5rem;
text-align: left;
+46
View File
@@ -0,0 +1,46 @@
/* Image optimization styles for S3 images */
/* Lazy loading fallback */
img[loading="lazy"] {
opacity: 0;
transition: opacity 0.3s;
}
img[loading="lazy"].loaded {
opacity: 1;
}
/* Improve gallery performance */
.gallery .img {
background-size: cover;
background-position: center;
background-repeat: no-repeat;
will-change: transform;
}
/* Responsive images */
img {
max-width: 100%;
height: auto;
display: block;
}
/* Placeholder while loading */
.gallery .img::before {
content: "";
display: block;
background: linear-gradient(90deg, #f0f0f0 25%, transparent 25%, transparent 50%, #f0f0f0 50%, #f0f0f0 75%, transparent 75%, transparent);
background-size: 20px 20px;
animation: loading 1s linear infinite;
}
@keyframes loading {
0% { background-position: 0 0; }
100% { background-position: 20px 0; }
}
/* Hide placeholder when image loads */
.gallery .img img {
position: relative;
z-index: 1;
}
+271
View File
@@ -0,0 +1,271 @@
/**
* Client-side файловое шифрование для форм
* Шифрует файлы в браузере пользователя перед отправкой
*/
class FileEncryption {
constructor() {
this.masterKey = 'sleeptrip_secure_key_2025'; // В продакшне должен быть более сложный
this.encryptedFiles = new Map(); // Хранилище зашифрованных файлов
}
/**
* Генерация криптографического ключа из мастер-пароля
*/
async generateKey(password, salt) {
const encoder = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey(
'raw',
encoder.encode(password),
'PBKDF2',
false,
['deriveKey']
);
return crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256'
},
keyMaterial,
{
name: 'AES-GCM',
length: 256
},
false,
['encrypt', 'decrypt']
);
}
/**
* Шифрование файла
*/
async encryptFile(file) {
try {
// Генерируем соль и IV
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
// Создаем ключ
const key = await this.generateKey(this.masterKey, salt);
// Читаем файл
const fileBuffer = await file.arrayBuffer();
// Шифруем
const encryptedData = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv
},
key,
fileBuffer
);
// Создаем метаданные
const metadata = {
fileName: file.name,
fileType: file.type,
fileSize: file.size,
encryptedAt: new Date().toISOString(),
salt: Array.from(salt),
iv: Array.from(iv)
};
// Комбинируем метаданные и зашифрованные данные
const metadataStr = JSON.stringify(metadata);
const metadataBytes = new TextEncoder().encode(metadataStr);
const metadataLength = new Uint32Array([metadataBytes.length]);
const result = new Uint8Array(
4 + metadataBytes.length + encryptedData.byteLength
);
result.set(new Uint8Array(metadataLength.buffer), 0);
result.set(metadataBytes, 4);
result.set(new Uint8Array(encryptedData), 4 + metadataBytes.length);
return {
encryptedData: result,
metadata: metadata,
originalName: file.name
};
} catch (error) {
console.error('Ошибка шифрования:', error);
throw error;
}
}
/**
* Инициализация шифрования для input элемента
*/
initFileInput(inputId) {
const input = document.getElementById(inputId);
const wrapper = input.closest('.file-input-wrapper');
const textElement = wrapper.querySelector('.file-input-text');
// Создаем контейнер для статуса шифрования
let statusDiv = wrapper.parentElement.querySelector('.encryption-status');
if (!statusDiv) {
statusDiv = document.createElement('div');
statusDiv.className = 'encryption-status';
wrapper.parentElement.appendChild(statusDiv);
}
input.addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
try {
// Показываем процесс шифрования
this.showEncryptionStatus(statusDiv, 'encrypting', 'Шифрование файла...');
textElement.textContent = `Шифрую: ${file.name}`;
textElement.className = 'file-input-text file-selected';
// Ждем немного для показа анимации
await new Promise(resolve => setTimeout(resolve, 500));
// Шифруем файл
const encryptedFile = await this.encryptFile(file);
// Сохраняем зашифрованный файл
this.encryptedFiles.set(inputId, encryptedFile);
// Обновляем UI
textElement.textContent = `${encryptedFile.originalName} (зашифрован)`;
textElement.className = 'file-input-text file-encrypted';
wrapper.classList.add('file-encrypted');
this.showEncryptionStatus(statusDiv, 'encrypted', '✅ Файл зашифрован и готов к отправке');
// Создаем скрытое поле с зашифрованными данными
this.createHiddenEncryptedField(input.form, inputId, encryptedFile);
} catch (error) {
console.error('Ошибка при шифровании файла:', error);
this.showEncryptionStatus(statusDiv, 'error', '❌ Ошибка шифрования файла');
textElement.textContent = 'Выберите файл';
textElement.className = 'file-input-text';
wrapper.classList.remove('file-encrypted');
}
});
}
/**
* Показ статуса шифрования
*/
showEncryptionStatus(statusDiv, type, message) {
statusDiv.className = `encryption-status ${type}`;
if (type === 'encrypting') {
statusDiv.innerHTML = `
<span class="encrypting-spinner"></span>
${message}
`;
} else {
statusDiv.textContent = message;
}
}
/**
* Создание скрытого поля с зашифрованными данными
*/
createHiddenEncryptedField(form, inputId, encryptedFile) {
// Удаляем предыдущее скрытое поле если есть
const existingField = form.querySelector(`input[name="${inputId}_encrypted"]`);
if (existingField) {
existingField.remove();
}
// Создаем новое скрытое поле
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = `${inputId}_encrypted`;
// Конвертируем зашифрованные данные в base64
const base64Data = btoa(String.fromCharCode(...encryptedFile.encryptedData));
hiddenField.value = base64Data;
form.appendChild(hiddenField);
// Также создаем поле с метаданными
const metadataField = document.createElement('input');
metadataField.type = 'hidden';
metadataField.name = `${inputId}_metadata`;
metadataField.value = JSON.stringify(encryptedFile.metadata);
form.appendChild(metadataField);
}
/**
* Получение зашифрованного файла по ID
*/
getEncryptedFile(inputId) {
return this.encryptedFiles.get(inputId);
}
/**
* Проверка наличия зашифрованных файлов перед отправкой формы
*/
validateEncryptedFiles(form) {
const fileInputs = form.querySelectorAll('input[type="file"]');
const encryptedFields = form.querySelectorAll('input[name$="_encrypted"]');
for (let input of fileInputs) {
if (input.files.length > 0) {
const encryptedField = form.querySelector(`input[name="${input.id}_encrypted"]`);
if (!encryptedField || !encryptedField.value) {
alert('Не все файлы зашифрованы. Пожалуйста, дождитесь завершения шифрования.');
return false;
}
}
}
return true;
}
}
// Инициализация при загрузке страницы
document.addEventListener('DOMContentLoaded', function() {
console.log('🔐 Инициализация системы шифрования...');
// Проверяем поддержку WebCrypto
if (!window.crypto || !window.crypto.subtle) {
console.error('❌ WebCrypto API не поддерживается в этом браузере');
alert('Ваш браузер не поддерживает шифрование. Используйте современный браузер.');
return;
}
const encryption = new FileEncryption();
// Инициализируем все file input элементы
const fileInputs = document.querySelectorAll('input[type="file"]');
console.log(`📂 Найдено ${fileInputs.length} файловых input элементов`);
fileInputs.forEach((input, index) => {
if (input.id) {
console.log(`🔧 Инициализируем шифрование для: ${input.id}`);
encryption.initFileInput(input.id);
} else {
console.warn(`⚠️ File input ${index} не имеет ID, пропускаем`);
}
});
// Добавляем валидацию к формам перед отправкой
const forms = document.querySelectorAll('form');
forms.forEach(form => {
form.addEventListener('submit', function(event) {
console.log('📤 Отправка формы, проверяем шифрование...');
if (!encryption.validateEncryptedFiles(form)) {
event.preventDefault();
return false;
}
});
});
// Делаем encryption доступным глобально для отладки
window.fileEncryption = encryption;
console.log('✅ Система шифрования инициализирована');
});
+104
View File
@@ -0,0 +1,104 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Тест шифрования файлов</title>
<link rel="stylesheet" href="/css/forms.css">
</head>
<body>
<div class="travel-form-container">
<h2>Тест системы шифрования файлов</h2>
<form class="contact-form" action="#" method="POST" onsubmit="return false;">
<div class="form-group">
<label for="name">Имя</label>
<input type="text" id="name" name="name" value="Тестовый пользователь">
</div>
<div class="form-group">
<label for="test_file">Тестовый файл для шифрования</label>
<div class="file-input-wrapper" onclick="document.getElementById('test_file').click()">
<input type="file" id="test_file" name="test_file" accept=".pdf,.jpg,.png,.txt" class="file-input-hidden">
<span class="file-input-text" id="test_file_text">Выберите файл для тестирования</span>
</div>
</div>
<div class="form-group">
<button type="submit" class="submit-btn">
Тестировать отправку
</button>
</div>
</form>
<div id="debug-info" style="margin-top: 2rem; padding: 1rem; background: #f8f9fa; border-radius: 8px;">
<h3>Отладочная информация:</h3>
<pre id="debug-content">Выберите файл для просмотра информации о шифровании</pre>
</div>
</div>
<script src="/js/encryption.js"></script>
<script>
// Дополнительная отладочная информация
document.addEventListener('DOMContentLoaded', function() {
const form = document.querySelector('.contact-form');
const debugContent = document.getElementById('debug-content');
// Перехватываем событие отправки формы для демонстрации
form.addEventListener('submit', function(event) {
event.preventDefault();
const formData = new FormData(form);
const encryptedField = form.querySelector('input[name="test_file_encrypted"]');
const metadataField = form.querySelector('input[name="test_file_metadata"]');
let debugInfo = 'Форма готова к отправке:\n\n';
for (let [key, value] of formData.entries()) {
if (key !== 'test_file') { // Не показываем оригинальный файл
debugInfo += `${key}: ${typeof value === 'string' ? value.substring(0, 100) + (value.length > 100 ? '...' : '') : '[File]'}\n`;
}
}
if (encryptedField) {
debugInfo += `\nЗашифрованные данные: ${encryptedField.value.length} символов (Base64)\n`;
}
if (metadataField) {
try {
const metadata = JSON.parse(metadataField.value);
debugInfo += '\nМетаданные файла:\n';
debugInfo += `- Имя: ${metadata.fileName}\n`;
debugInfo += `- Тип: ${metadata.fileType}\n`;
debugInfo += `- Размер: ${metadata.fileSize} байт\n`;
debugInfo += `- Зашифровано: ${metadata.encryptedAt}\n`;
} catch (e) {
debugInfo += '\nОшибка чтения метаданных\n';
}
}
debugContent.textContent = debugInfo;
alert('Тест завершен! Смотрите отладочную информацию ниже.');
});
// Отслеживаем изменения в шифровании
const fileInput = document.getElementById('test_file');
if (fileInput) {
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
const encryptedField = form.querySelector('input[name="test_file_encrypted"]');
if (encryptedField && encryptedField.value) {
debugContent.textContent = 'Файл зашифрован и готов к отправке!\nНажмите "Тестировать отправку" для просмотра деталей.';
}
}
});
});
observer.observe(form, { childList: true, subtree: true });
}
});
</script>
</body>
</html>