/
mitg
/
Pass
Обзор
Документация
Войти
/
mitg
/
Pass
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
index.html
569 строк
26 KB
mitg
create: server.js, index.html
29 май 2026, 16:21
Верифицирован
29 май 2026, 16:21
d3f9017
Код
Авторство
О чём код?
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Passkey Hub — Беспарольная аутентификация</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f5f7fb; color: #1e293b; padding: 30px 20px; } .container { max-width: 1300px; margin: 0 auto; } /* Карточки обычные, но с хорошими отступами */ .card { background: #ffffff; border-radius: 28px; box-shadow: 0 6px 14px rgba(0,0,0,0.05); margin-bottom: 28px; border: 1px solid #e2e8f0; overflow: hidden; } .card-header { padding: 20px 28px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; background: #fafcff; } .card-header h2, .card-header h3 { font-size: 22px; font-weight: 700; color: #0f172a; } .card-body { padding: 20px 28px; } /* Логотип и шапка */ .logo h1 { font-size: 32px; font-weight: 800; background: linear-gradient(135deg, #f97316, #ef4444); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .logo p { font-size: 14px; color: #475569; margin-top: 4px; } .tech-badge { background: #f1f5f9; padding: 8px 18px; border-radius: 40px; font-size: 14px; font-weight: 500; border: 1px solid #cbd5e1; } /* Сетка 3 колонки (для метрик и кейсов) */ .grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; margin-bottom: 24px; } /* Карточки метрик и кейсов (умеренно увеличены) */ .metric-card { background: #f8fafc; border-radius: 24px; padding: 24px 16px; text-align: center; border: 1px solid #e2e8f0; transition: 0.2s; } .metric-card:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(0,0,0,0.08); } .metric-icon { font-size: 48px; margin-bottom: 12px; } .metric-value { font-size: 36px; font-weight: 800; color: #f97316; margin-bottom: 6px; } .metric-label { font-size: 16px; font-weight: 500; color: #334155; } /* Кнопки */ .btn { padding: 12px 24px; border: none; border-radius: 60px; font-weight: 700; cursor: pointer; font-size: 16px; transition: 0.2s; } .btn-primary { background: linear-gradient(135deg, #f97316, #ef4444); color: white; } .btn-secondary { background: #e2e8f0; color: #1e293b; } .btn-outline { background: transparent; border: 1px solid #cbd5e1; color: #475569; } .btn-sm { padding: 8px 16px; font-size: 14px; } /* Инпут */ .input-modern { background: #ffffff; border: 1px solid #cbd5e1; border-radius: 60px; padding: 14px 20px; width: 100%; font-size: 16px; color: #0f172a; } .input-modern:focus { outline: none; border-color: #f97316; } /* Криптошаги (без изменений, они норм) */ .crypto-steps { display: flex; flex-direction: column; gap: 12px; } .step { display: flex; gap: 16px; padding: 16px; background: #f8fafc; border-radius: 20px; border-left: 5px solid #cbd5e1; } .step.active { border-left-color: #f97316; background: #fff7ed; } .step.completed { border-left-color: #22c55e; } .step-number { width: 34px; height: 34px; background: #e2e8f0; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 16px; } .step-title { font-weight: 700; font-size: 16px; margin-bottom: 4px; } .step-desc { font-size: 13px; color: #475569; } .step-code { font-family: monospace; font-size: 11px; background: #fff; padding: 6px 10px; border-radius: 12px; margin-top: 8px; border: 1px solid #e2e8f0; } /* Визуализация ключей */ .key-visual { display: flex; gap: 20px; justify-content: center; margin-top: 24px; flex-wrap: wrap; } .key-card { flex: 1; text-align: center; padding: 18px; background: #f8fafc; border-radius: 20px; border: 1px solid #e2e8f0; min-width: 220px; } .key-card.private { border-top: 4px solid #ef4444; } .key-card.public { border-top: 4px solid #22c55e; } .badge-private, .badge-public { display: inline-block; padding: 4px 10px; border-radius: 30px; font-size: 11px; margin-top: 12px; } .badge-private { background: #fee2e2; color: #b91c1c; } .badge-public { background: #dcfce7; color: #166534; } /* Лог */ .log-container { background: #f8fafc; border-radius: 18px; padding: 16px; max-height: 200px; overflow-y: auto; font-family: monospace; font-size: 13px; border: 1px solid #e2e8f0; } .log-entry { padding: 8px 0; border-bottom: 1px solid #e2e8f0; } .log-success { color: #16a34a; } .log-error { color: #dc2626; } .log-info { color: #2563eb; } .log-crypto { color: #ea580c; } .keys-list div { padding: 12px 0; border-bottom: 1px solid #e2e8f0; font-family: monospace; font-size: 14px; } .hidden { display: none; } .flex-between { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; } .avatar { width: 48px; height: 48px; background: linear-gradient(135deg, #f97316, #ef4444); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 22px; color: white; } /* БОЛЬШОЕ МОДАЛЬНОЕ ОКНО — для кейсов */ .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 1000; } .modal-content { background: white; max-width: 750px; width: 90%; border-radius: 40px; padding: 36px; border-top: 6px solid #f97316; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); } .modal-content h3 { font-size: 32px; margin-bottom: 20px; font-weight: 800; } .modal-content p, .modal-content li { font-size: 18px; line-height: 1.4; color: #1e293b; } .modal-content .detail-block { background: #f8fafc; padding: 20px; border-radius: 24px; margin: 20px 0; } .modal-content .detail-block strong { font-size: 20px; display: block; margin-bottom: 12px; } .modal-content .crypto-steps-demo { font-family: monospace; background: #f1f5f9; padding: 16px; border-radius: 20px; font-size: 16px; } .modal-content button { margin-top: 20px; font-size: 18px; padding: 14px 24px; width: 100%; } </style> </head> <body> <div class="container"> <!-- Панель входа --> <div id="loginPanel"> <div class="card"> <div class="card-header"> <div class="logo"> <h1>🔐 Passkey Hub</h1> <p>Беспарольная аутентификация WebAuthn / FIDO2</p> </div> <div class="tech-badge">Асимметричная криптография</div> </div> </div> <!-- Криптографическая демонстрация --> <div class="card"> <div class="card-header"> <h2>🔬 Криптографическая демонстрация</h2> <span id="stepCounter" style="color:#475569;">Шаг 1 из 6</span> </div> <div class="card-body"> <div class="crypto-steps" id="cryptoSteps"> <div class="step" id="step1"><div class="step-number">1</div><div class="step-content"><div class="step-title">📡 Запрос опций</div><div class="step-desc">Клиент запрашивает challenge и параметры</div></div></div> <div class="step" id="step2"><div class="step-number">2</div><div class="step-content"><div class="step-title">🎲 Генерация challenge</div><div class="step-desc">Сервер генерирует случайный challenge</div><div class="step-code" id="challengeValue">—</div></div></div> <div class="step" id="step3"><div class="step-number">3</div><div class="step-content"><div class="step-title">🔑 Генерация ключевой пары</div><div class="step-desc">Аутентификатор создаёт <span style="color:#ef4444;">приватный</span> + <span style="color:#22c55e;">публичный</span> ключи</div></div></div> <div class="step" id="step4"><div class="step-number">4</div><div class="step-content"><div class="step-title">✍️ Подписание challenge</div><div class="step-desc">Приватный ключ подписывает challenge</div></div></div> <div class="step" id="step5"><div class="step-number">5</div><div class="step-content"><div class="step-title">📤 Отправка на сервер</div><div class="step-desc">Передаётся публичный ключ + подпись</div></div></div> <div class="step" id="step6"><div class="step-number">6</div><div class="step-content"><div class="step-title">✅ Верификация</div><div class="step-desc">Сервер проверяет подпись и сохраняет ключ</div></div></div> </div> <div class="key-visual" id="keyVisual" style="display: none;"> <div class="key-card private"><h4>🔒 ПРИВАТНЫЙ КЛЮЧ</h4><p id="privateKeyDemo">—</p><div class="badge-private">НИКОГДА не покидает устройство</div></div> <div class="key-card public"><h4>🌍 ПУБЛИЧНЫЙ КЛЮЧ</h4><p id="publicKeyDemo">—</p><div class="badge-public">Хранится на сервере</div></div> </div> </div> </div> <!-- Форма --> <div class="card"> <div class="card-body"> <div style="max-width: 450px; margin: 0 auto;"> <input type="text" id="username" class="input-modern" placeholder="Имя пользователя (test, ivan, demo)" autocomplete="off" style="margin-bottom: 20px;"> <div style="display: flex; gap: 16px;"> <button class="btn btn-primary" id="registerBtn" style="flex:1;">📝 Создать пасс-ключ</button> <button class="btn btn-secondary" id="loginBtn" style="flex:1;">🔑 Войти</button> </div> <button class="btn btn-outline" id="demoNoKeyBtn" style="margin-top: 16px; width:100%;">⚠️ Демо: попытка входа без ключа</button> </div> </div> </div> <!-- Лог --> <div class="card"> <div class="card-header"><h3>📋 Криптографический лог</h3></div> <div class="card-body"><div class="log-container" id="log"><div class="log-entry"><span class="log-info">✅ Готов. Нажмите "Создать пасс-ключ"</span></div></div></div> </div> </div> <!-- Дашборд (после входа) --> <div id="dashboardPanel" class="hidden"> <div class="card"> <div class="card-header"> <div class="flex-between" style="width:100%;"> <div><h1 style="font-size:28px;">🏦 Passkey Hub</h1><p style="color:#475569; font-size:15px;">Защищённый личный кабинет</p></div> <div style="display:flex; align-items:center; gap:15px;"> <div class="avatar" id="userAvatar">👤</div> <div><div id="dashboardUsername" style="font-weight:700; font-size:18px;">Пользователь</div><div style="font-size:14px; color:#16a34a;">✓ Пасс-ключ активен</div></div> <button class="btn btn-outline btn-sm" id="logoutBtn">Выйти</button> </div> </div> </div> </div> <div class="grid-3"> <div class="metric-card"><div class="metric-icon">🔑</div><div class="metric-value" id="keyCount">0</div><div class="metric-label">Пасс-ключей</div></div> <div class="metric-card"><div class="metric-icon">📅</div><div class="metric-value" id="sessionTime">-</div><div class="metric-label">Время сессии</div></div> <div class="metric-card"><div class="metric-icon">🛡️</div><div class="metric-value">FIDO2</div><div class="metric-label">Аппаратная защита</div></div> </div> <div class="card"> <div class="card-header"><h3>🔐 Мои пасс-ключи</h3><button class="btn btn-primary btn-sm" id="addKeyBtn">+ Добавить</button></div> <div class="card-body"><div id="keysList" class="keys-list">Загрузка...</div></div> </div> <div class="card"> <div class="card-header"><h3>💼 Защищённые действия (кейсы)</h3></div> <div class="card-body"> <div class="grid-3"> <div class="metric-card" style="cursor:pointer;" data-action="transfer"> <div class="metric-icon">💰</div> <div class="metric-value">Перевод</div> <div class="metric-label">Банковский перевод</div> </div> <div class="metric-card" style="cursor:pointer;" data-action="settings"> <div class="metric-icon">⚙️</div> <div class="metric-value">Настройки</div> <div class="metric-label">Изменение профиля</div> </div> <div class="metric-card" style="cursor:pointer;" data-action="api"> <div class="metric-icon">🔑</div> <div class="metric-value">API-ключ</div> <div class="metric-label">Генерация токена</div> </div> </div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/@simplewebauthn/browser@9.0.1/dist/bundle/index.umd.min.js"></script> <script> const { startRegistration, startAuthentication } = SimpleWebAuthnBrowser; let currentUser = null, sessionStart = null; const loginPanel = document.getElementById('loginPanel'); const dashboardPanel = document.getElementById('dashboardPanel'); const logDiv = document.getElementById('log'); function addLog(msg, type='info'){ const time=new Date().toLocaleTimeString('ru-RU'); logDiv.innerHTML=`<div class="log-entry"><span class="log-time">[${time}]</span> <span class="log-${type}">${msg}</span></div>`+logDiv.innerHTML; } function updateStep(stepNum, isActive, extra){ for(let i=1;i<=6;i++){ let s=document.getElementById(`step${i}`); if(s){ s.classList.remove('active','completed'); if(i<stepNum) s.classList.add('completed'); } } let cs=document.getElementById(`step${stepNum}`); if(cs&&isActive) cs.classList.add('active'); document.getElementById('stepCounter').innerText=`Шаг ${stepNum} из 6`; if(extra?.challenge) document.getElementById('challengeValue').innerHTML=`Challenge: ${extra.challenge.substring(0,32)}...`; } function resetSteps(){ for(let i=1;i<=6;i++){ let s=document.getElementById(`step${i}`); if(s) s.classList.remove('active','completed'); } document.getElementById('step1')?.classList.add('active'); document.getElementById('stepCounter').innerText='Шаг 1 из 6'; document.getElementById('keyVisual').style.display='none'; } async function register(){ const username=document.getElementById('username').value.trim(); if(!username){ addLog('❌ Введите имя','error'); return; } resetSteps(); updateStep(1,true); addLog('📡 Шаг1: Запрос опций...','crypto'); try{ const res=await fetch('/register/options',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username})}); if(!res.ok) throw new Error(await res.text()); const options=await res.json(); updateStep(2,true,{challenge:options.challenge}); addLog(`🎲 Шаг2: Challenge получен`,'crypto'); updateStep(3,true); addLog('🔑 Шаг3: Генерация ключевой пары...','crypto'); const attestation=await startRegistration(options); updateStep(4,true); addLog('✍️ Шаг4: Подписание challenge','crypto'); updateStep(5,true); addLog('📤 Шаг5: Отправка на сервер','crypto'); const verifyRes=await fetch('/register/verify',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(attestation)}); const result=await verifyRes.json(); updateStep(6,true,true); if(result.verified){ addLog('✅ Шаг6: Сервер проверил подпись и сохранил публичный ключ!','success'); document.getElementById('keyVisual').style.display='flex'; document.getElementById('publicKeyDemo').innerHTML=attestation.id.substring(0,40)+'...'; addLog('🔐 Пасс-ключ создан! Теперь можно войти','success'); } else addLog('❌ Ошибка верификации','error'); } catch(err){ addLog(`❌ ${err.message}`,'error'); } } async function login(){ const username=document.getElementById('username').value.trim(); if(!username){ addLog('❌ Введите имя','error'); return; } addLog('🔑 Запрос опций входа...','info'); try{ const res=await fetch('/login/options',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username})}); if(!res.ok) throw new Error(await res.text()); const options=await res.json(); addLog('🔏 Используйте пасс-ключ для подписи...','crypto'); const assertion=await startAuthentication(options); addLog('✅ Отправка на сервер...','info'); const verifyRes=await fetch('/login/verify',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(assertion)}); const result=await verifyRes.json(); if(result.verified){ addLog(`✅ Вход выполнен! Привет, ${result.username}!`,'success'); addLog(`🔐 Приватный ключ не покидал устройство`,'crypto'); await showDashboard(result.username); } else addLog('❌ Ошибка входа','error'); } catch(err){ addLog(`❌ ${err.message}`,'error'); } } async function demoNoKey(){ const username=document.getElementById('username').value.trim(); if(!username){ addLog('❌ Введите имя','error'); return; } try{ const res=await fetch('/check-user',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username})}); const data=await res.json(); if(!data.exists) addLog('❌ Пользователь не найден','error'); else if(!data.hasKeys) addLog('❌ Нет пасс-ключей — вход невозможен','error'); else addLog('⚠️ Ключи есть, но без пасс-ключа войти нельзя!','warning'); } catch(e){ addLog(`❌ ${e.message}`,'error'); } } async function loadUserKeys(){ if(!currentUser) return; const res=await fetch(`/user/keys?username=${currentUser}`); const keys=await res.json(); document.getElementById('keyCount').innerHTML=keys.length; const div=document.getElementById('keysList'); if(keys.length===0) div.innerHTML='Нет ключей'; else div.innerHTML=keys.map(k=>`<div>🔑 ${k.id.substring(0,36)}... (создан ${new Date(k.created_at).toLocaleDateString()})</div>`).join(''); } async function showDashboard(username){ currentUser=username; sessionStart=new Date(); document.getElementById('dashboardUsername').innerText=username; document.getElementById('userAvatar').innerText=username.charAt(0).toUpperCase(); document.getElementById('sessionTime').innerHTML=sessionStart.toLocaleTimeString(); await loadUserKeys(); loginPanel.classList.add('hidden'); dashboardPanel.classList.remove('hidden'); addLog('🏠 Добро пожаловать в личный кабинет!','success'); } function hideDashboard(){ currentUser=null; dashboardPanel.classList.add('hidden'); loginPanel.classList.remove('hidden'); resetSteps(); addLog('👋 Сессия завершена','info'); } // БОЛЬШИЕ МОДАЛЬНЫЕ ОКНА ДЛЯ КЕЙСОВ function showCaseModal(action) { const cases = { transfer: { title: '💰 Банковский перевод', description: 'В реальном банковском приложении операция перевода требует повторной криптографической подписи через пасс-ключ (двухфакторная аутентификация).', crypto: 'Сервер генерирует новый случайный challenge → браузер вызывает WebAuthn → пользователь подтверждает подпись (Touch ID / PIN) → подпись отправляется на сервер → сервер верифицирует подпись публичным ключом → перевод выполняется.', demoData: 'Сумма: 15 000 ₽ | Получатель: Иванов И.И. | Назначение: оплата услуг', steps: '1. Пользователь заполняет форму перевода и нажимает "Подтвердить"\n2. Бэкенд создаёт challenge, привязанный к операции\n3. Браузер показывает диалог пасс-ключа\n4. Пользователь сканирует отпечаток / вводит PIN\n5. Подпись отправляется и проверяется\n6. Банк списывает средства' }, settings: { title: '⚙️ Изменение профиля', description: 'Критическое изменение (email, телефон, пароль) требует подтверждения, что сессия не перехвачена.', crypto: 'Аналогично переводу: создаётся challenge → подпись → верификация. Даже если злоумышленник уже в личном кабинете, он не сможет изменить данные без физического подтверждения.', demoData: 'Новый email: newuser@example.com | Новый телефон: +7 999 123-45-67', steps: '1. Пользователь вводит новые данные\n2. Сервер запрашивает подпись через WebAuthn\n3. Пользователь подтверждает действие пасс-ключом\n4. После верификации данные обновляются' }, api: { title: '🔑 Генерация API-ключа', description: 'Выпуск токена доступа — чувствительная операция, доступная только после криптографического подтверждения.', crypto: 'Требуется подпись challenge пасс-ключом, чтобы исключить автоматическую генерацию ключей вредоносным ПО.', demoData: 'Новый API-ключ: pk_live_3f8a2d1c5b9e... (скопирован в буфер)', steps: '1. Пользователь запрашивает API-ключ\n2. Сервер отправляет challenge\n3. WebAuthn запрашивает подпись\n4. Подтверждение → генерация и отображение ключа' } }; const c = cases[action]; if (!c) return; const modal = document.createElement('div'); modal.className = 'modal-overlay'; modal.innerHTML = ` <div class="modal-content"> <h3>${c.title}</h3> <div class="detail-block"> <strong>📌 Сценарий использования</strong> <p>${c.description}</p> </div> <div class="detail-block"> <strong>🔐 Криптографическая подпись</strong> <p>${c.crypto}</p> </div> <div class="detail-block"> <strong>📄 Демонстрационные данные</strong> <div class="crypto-steps-demo">${c.demoData}</div> </div> <div class="detail-block"> <strong>⚙️ Реальный протокол (шаги)</strong> <div class="crypto-steps-demo" style="white-space: pre-line;">${c.steps}</div> </div> <button class="btn btn-primary" onclick="this.closest('.modal-overlay').remove()">Закрыть</button> </div> `; document.body.appendChild(modal); addLog(`🔐 Открыта детальная информация по кейсу: ${c.title}`, 'success'); } // Навешиваем обработчики на карточки кейсов document.querySelectorAll('.metric-card[data-action]').forEach(card => { const action = card.getAttribute('data-action'); card.onclick = () => showCaseModal(action); }); document.getElementById('registerBtn').onclick = register; document.getElementById('loginBtn').onclick = login; document.getElementById('demoNoKeyBtn').onclick = demoNoKey; document.getElementById('logoutBtn').onclick = hideDashboard; document.getElementById('addKeyBtn').onclick = register; resetSteps(); </script> </body> </html>