Files
quizz/code_artifact.html
2026-10-10 22:42:35 +05:00

898 lines
54 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CyberGuard | Интерактивный тест по цифровой безопасности</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
cyber: {
900: '#060a12',
850: '#0c1322',
800: '#111a30',
700: '#1b2848',
accent: '#06b6d4',
emerald: '#10b981',
rose: '#f43f5e',
glow: 'rgba(6, 182, 212, 0.15)'
}
},
fontFamily: {
sans: ['Inter', 'system-ui', '-apple-system', 'Segoe UI', 'Roboto', 'sans-serif'],
mono: ['JetBrains Mono', 'ui-monospace', 'monospace']
}
}
}
}
</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
<style>
body {
background-color: #060a12;
background-image:
radial-gradient(circle at 15% 20%, rgba(6, 182, 212, 0.08) 0%, transparent 45%),
radial-gradient(circle at 85% 80%, rgba(16, 185, 129, 0.07) 0%, transparent 45%),
linear-gradient(to bottom, rgba(6, 10, 18, 0.8), #060a12);
min-height: 100vh;
font-family: 'Inter', sans-serif;
}
.glass-card {
background: rgba(17, 26, 48, 0.7);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.08);
}
.glass-pill {
background: rgba(255, 255, 255, 0.04);
border: 1px solid rgba(255, 255, 255, 0.07);
}
.option-btn {
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}
.option-btn:hover:not(:disabled) {
transform: translateY(-2px);
border-color: rgba(6, 182, 212, 0.5);
box-shadow: 0 8px 24px -6px rgba(6, 182, 212, 0.2);
}
@keyframes pulseGlow {
0%, 100% { opacity: 0.4; }
50% { opacity: 0.8; }
}
.glow-dot {
animation: pulseGlow 2s infinite ease-in-out;
}
/* Custom scrollbar for review modal/sections */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: #0c1322;
}
::-webkit-scrollbar-thumb {
background: #1b2848;
border-radius: 9999px;
}
</style>
</head>
<body class="text-slate-100 flex flex-col justify-between p-4 sm:p-6 md:p-8 antialiased selection:bg-cyan-500 selection:text-black">
<!-- Header & Navigation Bar -->
<header class="max-w-4xl w-full mx-auto flex items-center justify-between py-2 mb-6">
<div class="flex items-center space-x-3">
<div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-cyan-500 to-emerald-400 p-[1px] flex items-center justify-center shadow-lg shadow-cyan-500/20">
<div class="w-full h-full bg-cyber-900 rounded-[11px] flex items-center justify-center">
<svg class="w-5 h-5 text-cyan-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z" />
</svg>
</div>
</div>
<div>
<h1 class="text-lg font-bold tracking-tight bg-gradient-to-r from-white via-slate-100 to-slate-400 bg-clip-text text-transparent">CyberGuard</h1>
<p class="text-xs text-cyan-400/80 font-mono tracking-wider uppercase">Security IQ Assessment</p>
</div>
</div>
<!-- Right Controls: Audio Toggle & Reset -->
<div class="flex items-center space-x-2">
<button id="soundToggleBtn" class="glass-pill px-3 py-2 rounded-xl text-xs flex items-center space-x-1.5 text-slate-300 hover:text-white hover:bg-white/10 transition-colors" title="Переключить звук">
<svg id="soundIconOn" class="w-4 h-4 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072M18.364 5.636a9 9 0 010 12.728M11 5L6 9H2v6h4l5 4V5z"/>
</svg>
<svg id="soundIconOff" class="w-4 h-4 text-slate-500 hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"/>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"/>
</svg>
<span class="font-mono text-[11px] hidden sm:inline" id="soundLabel">Звук: ВКЛ</span>
</button>
<button id="restartQuickBtn" class="glass-pill px-3 py-2 rounded-xl text-xs flex items-center space-x-1.5 text-slate-300 hover:text-white hover:bg-white/10 transition-colors" title="Начать заново">
<svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
</svg>
<span class="hidden sm:inline">Сброс</span>
</button>
</div>
</header>
<main class="max-w-4xl w-full mx-auto my-auto flex flex-col justify-center">
<!-- Screen 1: Start Screen -->
<section id="startScreen" class="glass-card rounded-3xl p-6 sm:p-10 text-center relative overflow-hidden shadow-2xl border border-white/10">
<div class="absolute -top-24 -left-24 w-60 h-60 bg-cyan-500/10 rounded-full blur-3xl pointer-events-none"></div>
<div class="absolute -bottom-24 -right-24 w-60 h-60 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none"></div>
<div class="inline-flex items-center space-x-2 px-3 py-1.5 rounded-full bg-cyan-500/10 border border-cyan-500/20 text-cyan-400 text-xs font-mono uppercase tracking-widest mb-6">
<span class="w-2 h-2 rounded-full bg-cyan-400 glow-dot"></span>
<span>Тест без банальных вопросов</span>
</div>
<h2 class="text-3xl sm:text-4xl md:text-5xl font-extrabold tracking-tight mb-4 leading-tight">
Насколько уязвимы ваши <br class="hidden sm:inline">
<span class="bg-gradient-to-r from-cyan-400 via-teal-300 to-emerald-400 bg-clip-text text-transparent">повседневные привычки?</span>
</h2>
<p class="text-slate-300 text-sm sm:text-base max-w-2xl mx-auto mb-8 leading-relaxed">
Забудьте про скучные вопросы вроде «придумывайте сложные пароли». Здесь собраны 7 реальных бытовых ситуаций: от коварных зарядок в аэропорту и «безобидных» умных лампочек до омоглифов и перевыпуска сим-карт.
</p>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4 max-w-xl mx-auto mb-8 text-left">
<div class="glass-pill p-3.5 rounded-2xl flex items-center space-x-3">
<div class="w-8 h-8 rounded-lg bg-cyan-500/15 flex items-center justify-center text-cyan-400 font-mono text-sm font-bold">7</div>
<div class="text-xs">
<p class="text-slate-400">Количество кейсов</p>
<p class="font-semibold text-slate-200">Практические задачи</p>
</div>
</div>
<div class="glass-pill p-3.5 rounded-2xl flex items-center space-x-3">
<div class="w-8 h-8 rounded-lg bg-emerald-500/15 flex items-center justify-center text-emerald-400 font-mono text-sm font-bold">~3</div>
<div class="text-xs">
<p class="text-slate-400">Время прохождения</p>
<p class="font-semibold text-slate-200">Минуты на тест</p>
</div>
</div>
<div class="glass-pill p-3.5 rounded-2xl flex items-center space-x-3">
<div class="w-8 h-8 rounded-lg bg-indigo-500/15 flex items-center justify-center text-indigo-400 font-mono text-sm font-bold">100%</div>
<div class="text-xs">
<p class="text-slate-400">Разбор ошибок</p>
<p class="font-semibold text-slate-200">Понятным языком</p>
</div>
</div>
</div>
<button id="startQuizBtn" class="group relative inline-flex items-center justify-center px-8 py-4 text-base font-bold text-cyber-900 transition-all duration-300 bg-gradient-to-r from-cyan-400 to-emerald-400 rounded-2xl shadow-xl shadow-cyan-500/25 hover:shadow-cyan-500/40 hover:scale-[1.02] active:scale-[0.98]">
<span>Начать проверку</span>
<svg class="w-5 h-5 ml-2 transition-transform duration-300 group-hover:translate-x-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M14 5l7 7m0 0l-7 7m7-7H3"/>
</svg>
</button>
</section>
<!-- Screen 2: Quiz Question Screen (hidden initially) -->
<section id="quizScreen" class="hidden flex flex-col space-y-5">
<!-- Progress bar & question index tracker -->
<div class="glass-card rounded-2xl p-4 flex flex-col space-y-3">
<div class="flex items-center justify-between text-xs font-mono">
<div class="flex items-center space-x-2 text-cyan-400">
<span class="w-2 h-2 rounded-full bg-cyan-400 glow-dot"></span>
<span>ВОПРОС <span id="currentQuestionNumber">1</span> ИЗ <span id="totalQuestionsCount">7</span></span>
</div>
<div class="text-slate-400">
Правильных: <span id="liveScore" class="font-bold text-emerald-400">0</span>
</div>
</div>
<!-- Visual Step Bar -->
<div class="w-full bg-cyber-850 h-2.5 rounded-full overflow-hidden p-[1px] border border-white/5">
<div id="progressBar" class="bg-gradient-to-r from-cyan-500 to-emerald-400 h-full rounded-full transition-all duration-500 ease-out" style="width: 14%;"></div>
</div>
<!-- Question Navigation Dots -->
<div id="questionDots" class="flex items-center justify-center space-x-1.5 sm:space-x-2 pt-1">
<!-- Filled dynamically via JS -->
</div>
</div>
<!-- Main Question Container -->
<div class="glass-card rounded-3xl p-6 sm:p-8 relative overflow-hidden shadow-2xl border border-white/10">
<!-- Tag and Situation title -->
<div class="flex flex-wrap items-center gap-2 mb-3">
<span id="questionCategory" class="px-3 py-1 rounded-full text-xs font-mono uppercase tracking-wider bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">
Физическая безопасность
</span>
<span id="difficultyBadge" class="px-2.5 py-0.5 rounded-full text-[11px] font-mono text-slate-400 glass-pill">
Уровень: Неожиданный
</span>
</div>
<!-- Question prompt -->
<h3 id="questionText" class="text-lg sm:text-2xl font-bold tracking-tight text-white mb-2 leading-snug">
Телефон почти разрядился. На вокзале вы видите стойку с бесплатными разъемами USB-A для зарядки. Как безопаснее поступить?
</h3>
<p id="questionContext" class="text-xs sm:text-sm text-slate-400 mb-6">
Ситуация из жизни: спешка, поезд через 20 минут, заряд 3%.
</p>
<!-- Options Container -->
<div id="optionsContainer" class="grid grid-cols-1 gap-3.5 mb-6">
<!-- Options dynamically rendered here -->
</div>
<!-- Feedback & Explanation Card (Initially hidden) -->
<div id="explanationContainer" class="hidden rounded-2xl p-4 sm:p-5 transition-all duration-300 border mb-6">
<div class="flex items-start space-x-3">
<div id="explanationIcon" class="w-8 h-8 rounded-xl flex-shrink-0 flex items-center justify-center mt-0.5">
<!-- Result Icon -->
</div>
<div class="flex-1">
<div class="flex items-center justify-between mb-1">
<h4 id="explanationTitle" class="text-sm sm:text-base font-bold">Верно!</h4>
<span id="threatTag" class="text-[11px] font-mono uppercase tracking-wider px-2 py-0.5 rounded">Juice Jacking</span>
</div>
<p id="explanationBody" class="text-xs sm:text-sm leading-relaxed text-slate-200 mb-2">
Объяснение...
</p>
<div class="text-[11px] sm:text-xs text-cyan-300/90 font-mono bg-cyan-950/40 p-2.5 rounded-xl border border-cyan-500/20 flex items-center space-x-2">
<svg class="w-4 h-4 flex-shrink-0 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
<span id="securityTip">Совет: Используйте проводные адаптеры блокировки данных (USB data blocker).</span>
</div>
</div>
</div>
</div>
<!-- Bottom Actions -->
<div class="flex items-center justify-between pt-2 border-t border-white/5">
<div class="text-xs text-slate-500 font-mono">
Кликните по варианту для выбора
</div>
<button id="nextQuestionBtn" class="hidden px-6 py-2.5 rounded-xl font-semibold text-sm bg-gradient-to-r from-cyan-400 to-emerald-400 text-cyber-900 hover:shadow-lg hover:shadow-cyan-500/25 transition-all duration-200 transform hover:scale-[1.02] active:scale-[0.98] items-center space-x-2">
<span id="nextBtnText">Следующий вопрос</span>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
</svg>
</button>
</div>
</div>
</section>
<!-- Screen 3: Results & Analytics Screen (hidden initially) -->
<section id="resultsScreen" class="hidden glass-card rounded-3xl p-6 sm:p-10 shadow-2xl border border-white/10 relative overflow-hidden">
<div class="text-center max-w-xl mx-auto mb-8">
<div class="inline-flex p-3 rounded-2xl bg-gradient-to-tr from-cyan-500/20 to-emerald-500/20 border border-cyan-500/30 mb-4 shadow-lg shadow-cyan-500/10">
<svg id="trophyIcon" class="w-12 h-12 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"/>
</svg>
</div>
<h2 class="text-2xl sm:text-3xl font-extrabold text-white mb-2">Анализ цифровой грамотности завершен</h2>
<p id="rankSubtitle" class="text-slate-300 text-sm sm:text-base">Ваш уровень устойчивости к киберугрозам</p>
</div>
<!-- Score stats grid -->
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
<div class="glass-pill p-4 rounded-2xl text-center border border-white/5">
<p class="text-xs text-slate-400 font-mono uppercase mb-1">Ваш результат</p>
<div class="text-3xl font-extrabold bg-gradient-to-r from-cyan-400 to-emerald-400 bg-clip-text text-transparent">
<span id="finalScoreNumber">0</span> / 7
</div>
<p id="finalScorePercent" class="text-xs text-slate-400 mt-1">0% правильных</p>
</div>
<div class="glass-pill p-4 rounded-2xl text-center border border-white/5 sm:col-span-2 flex flex-col justify-center">
<p class="text-xs text-slate-400 font-mono uppercase mb-1">Присвоенный статус</p>
<div id="rankTitle" class="text-xl sm:text-2xl font-bold text-white tracking-tight">
Осторожный пользователь
</div>
<p id="rankDescription" class="text-xs text-slate-300 mt-1 leading-relaxed">
Вы хорошо ориентируетесь в основных опасностях, но некоторые нестандартные сценарии могут застать вас врасплох.
</p>
</div>
</div>
<!-- Detailed Breakdown List -->
<div class="mb-8">
<div class="flex items-center justify-between mb-4">
<h3 class="text-base font-bold text-slate-200">Разбор ответов и ключевые уроки:</h3>
<span class="text-xs font-mono text-slate-400">7 ситуаций</span>
</div>
<div id="answersReviewList" class="space-y-3 max-h-96 overflow-y-auto pr-1">
<!-- Filled dynamically by JavaScript -->
</div>
</div>
<!-- Action Buttons -->
<div class="flex flex-col sm:flex-row items-center justify-center gap-3 pt-4 border-t border-white/5">
<button id="retakeQuizBtn" class="w-full sm:w-auto px-8 py-3.5 rounded-xl font-bold text-sm bg-gradient-to-r from-cyan-400 to-emerald-400 text-cyber-900 hover:shadow-lg hover:shadow-cyan-500/25 transition-all transform hover:scale-[1.02] active:scale-[0.98]">
Пройти тест еще раз
</button>
<button id="copyResultsBtn" class="w-full sm:w-auto px-6 py-3.5 rounded-xl font-semibold text-sm glass-pill text-slate-300 hover:text-white hover:bg-white/10 transition-colors flex items-center justify-center space-x-2">
<svg class="w-4 h-4 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"/>
</svg>
<span id="copyBtnText">Скопировать результат</span>
</button>
</div>
</section>
</main>
<!-- Footer -->
<footer class="max-w-4xl w-full mx-auto text-center py-4 mt-6 text-xs text-slate-500">
<p>Информационная безопасность — это привычки, а не сложное ПО. Защищайте свои данные грамотно.</p>
</footer>
<script>
// Audio synthesizer helper (Web Audio API - no external assets required)
const SoundEngine = {
enabled: true,
ctx: null,
init() {
if (!this.ctx) {
const AudioContext = window.AudioContext || window.webkitAudioContext;
if (AudioContext) {
this.ctx = new AudioContext();
}
}
},
play(type) {
if (!this.enabled) return;
this.init();
if (!this.ctx) return;
if (this.ctx.state === 'suspended') {
this.ctx.resume();
}
const now = this.ctx.currentTime;
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.connect(gain);
gain.connect(this.ctx.destination);
if (type === 'click') {
osc.type = 'sine';
osc.frequency.setValueAtTime(440, now);
osc.frequency.exponentialRampToValueAtTime(880, now + 0.05);
gain.gain.setValueAtTime(0.08, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
osc.start(now);
osc.stop(now + 0.05);
} else if (type === 'correct') {
osc.type = 'triangle';
osc.frequency.setValueAtTime(523.25, now); // C5
osc.frequency.setValueAtTime(659.25, now + 0.08); // E5
osc.frequency.setValueAtTime(783.99, now + 0.16); // G5
gain.gain.setValueAtTime(0.12, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.35);
osc.start(now);
osc.stop(now + 0.35);
} else if (type === 'wrong') {
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(260, now);
osc.frequency.setValueAtTime(195, now + 0.12);
gain.gain.setValueAtTime(0.1, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
osc.start(now);
osc.stop(now + 0.3);
} else if (type === 'complete') {
// victory chime
const notes = [523.25, 659.25, 783.99, 1046.50];
notes.forEach((freq, idx) => {
const o = this.ctx.createOscillator();
const g = this.ctx.createGain();
o.type = 'triangle';
o.frequency.value = freq;
o.connect(g);
g.connect(this.ctx.destination);
const start = now + (idx * 0.09);
g.gain.setValueAtTime(0.12, start);
g.gain.exponentialRampToValueAtTime(0.001, start + 0.28);
o.start(start);
o.stop(start + 0.28);
});
}
}
};
// Complete Database of 7 Practical Cybersecurity Questions
const questions = [
{
id: 1,
category: "Физическая безопасность",
threat: "Juice Jacking (Взлом через зарядку)",
question: "Телефон почти разрядился. На вокзале вы видите стойку с бесплатными разъемами USB-A для зарядки. Как безопаснее поступить?",
context: "Ситуация: до отправления 20 минут, нужно зарядить смартфон до вызова такси.",
options: [
{ text: "Подключиться напрямую: USB-порт передает только ток и физически не может считывать файлы.", correct: false },
{ text: "Подключить телефон через свой блок питания в розетку 220В или взять повербанк.", correct: true },
{ text: "Подключиться кабелем, но сразу включить «Авиарежим» для блокировки утечки данных.", correct: false },
{ text: "Подключиться, заблокировать экран и не трогать телефон до полной зарядки.", correct: false }
],
explanation: "Кабель и порт USB содержат не только линии питания, но и контакты передачи данных. Через взломанный разъем злоумышленники могут незаметно выгрузить фотографии, переписки или установить вредоносную прошивку (атака Juice Jacking).",
tip: "Розетка 220В передает только переменный ток. Также для общественных USB можно использовать USB-презерватив (USB Data Blocker) — переходник без контактов передачи данных."
},
{
id: 2,
category: "Социальная инженерия и OSINT",
threat: "Секретные контрольные вопросы",
question: "Вы часто заказываете кофе в приложении, и ваша карта лояльности названа вашей девичьей фамилией или кличкой первой собаки. В чем скрытая опасность?",
context: "Ситуация: безобидная анкета в кофейне, фитнес-клубе или профиле доставки пиццы.",
options: [
{ text: "Никакой опасности нет: базы скидочных карт не связаны с банковскими счетами.", correct: false },
{ text: "Кассир кофейни может скопировать эти данные и мгновенно оформить на вас кредит.", correct: false },
{ text: "Эти же факты люди по привычке используют как секретные ответы для сброса паролей к почте и сервисам.", correct: true },
{ text: "Маркетологи смогут взломать телефон через уведомления от приложения кофейни.", correct: false }
],
explanation: "«Девичья фамилия матери», «кличка первого питомца», «школа №42» — это стандартные контрольные вопросы для сброса паролей. Утечки из ресторанных баз или посты в соцсетях позволяют хакерам легко собрать это досье и сбросить доступ к вашей почте.",
tip: "Никогда не пишите правду в секретных вопросах. Используйте бессмысленный набор слов (например, «первая собака — фиолетовый_трактор_88») и сохраняйте его в менеджере паролей."
},
{
id: 3,
category: "Аппаратные атаки (Hardware)",
threat: "BadUSB / Rubber Ducky",
question: "Возле входа в офис или на парковке лежит новенькая флешка с аккуратной наклейкой «Зарплаты_и_Премии_2024». Ваши действия?",
context: "Ситуация: любопытство велико, флешка выглядит новой и дорогой.",
options: [
{ text: "Вставить в рабочий ПК, но мгновенно запустить полное сканирование антивирусом.", correct: false },
{ text: "Вставить в домашний ноутбук: там нет коммерческих тайн, значит, риск минимален.", correct: false },
{ text: "Вставить, но ни в коем случае не открывать и не кликать на файлы внутри.", correct: false },
{ text: "Никуда не подключать. Выбросить или передать системному администратору / ИБ-службе.", correct: true }
],
explanation: "Подброшенная флешка часто является не накопителем, а микроконтроллером типа Rubber Ducky (BadUSB). В момент включения она притворяется клавиатурой и за доли секунды вбивает вредоносные системные команды еще до того, как сработает любой антивирус.",
tip: "Никогда не вставляйте найденные или подаренные неизвестными флешки в свои устройства. Ни домашний, ни рабочий ПК не защищены от эмуляции аппаратной клавиатуры."
},
{
id: 4,
category: "Управление цифровой личностью",
threat: "Рециркуляция номеров (SIM Recycling)",
question: "Вы перешли к другому оператору и забросили старую сим-карту. Через полгода вам на почту начали приходить уведомления о сбросе паролей. Почему?",
context: "Ситуация: старый номер лежал в тумбочке, баланс обнулился.",
options: [
{ text: "Хакеры взломали базовые вышки связи и перехватили старые радиосигналы.", correct: false },
{ text: "Оператор перепродал неактивный номер новому абоненту, и тот нажал «Восстановить доступ».", correct: true },
{ text: "Сим-карта физически размагнитилась и случайно отправила пакет с паролями в сеть.", correct: false },
{ text: "Это автоматическая системная рассылка, на нее не нужно обращать внимания.", correct: false }
],
explanation: "По закону и договорам связи, если номер неактивен 3–6 месяцев, оператор вправе вернуть его в пул свободных номеров и продать другому человеку. Новый владелец может просто нажимать «Вход по СМС» в Telegram, маркетплейсах и банках.",
tip: "Перед тем как отказаться от номера телефона, методично отвяжите его от Госуслуг, мессенджеров, почты, банков и онлайн-магазинов, либо переведите тариф на минимальный без абонплаты для сохранения."
},
{
id: 5,
category: "Сетевая безопасность и IoT",
threat: "Взлом через Интернет вещей (IoT Botnets)",
question: "Вы купили пару недорогих умных Wi-Fi розеток, робот-пылесос и смарт-лампу. Как настроить домашний роутер для максимальной защиты?",
context: "Ситуация: устройства работают по Wi-Fi 2.4 ГГц и постоянно отправляют данные на серверы производителя.",
options: [
{ text: "Ничего не настраивать: лампочка физически не имеет доступа к паролям на ноутбуке.", correct: false },
{ text: "Подключить все умные устройства к изолированной «гостевой» сети Wi-Fi.", correct: true },
{ text: "Выключать домашний роутер из розетки каждый раз перед сном.", correct: false },
{ text: "Менять пароль от Wi-Fi каждые 3 дня, вводя его вручную на пылесосе.", correct: false }
],
explanation: "Дешевые IoT-устройства редко получают патчи безопасности и часто имеют заводские уязвимости. Если хакер взломает умную розетку, находясь в общей домашней сети, он сможет перехватить трафик с вашего ПК или атаковать сетевой диск (NAS).",
tip: "Включите в роутере функцию «Гостевая сеть» (Guest Network) с изоляцией клиентов (AP Isolation) и выделите ее только под умный дом. Компьютеры и телефоны оставьте в основной сети."
},
{
id: 6,
category: "Фишинг и социальная инженерия",
threat: "Омоглифы (IDN Homograph Attack)",
question: "Знакомый прислал ссылку вроде «gооgle.com/promo». Внешне домен привычный, но браузер или антивирус бьет тревогу. В чем подвох?",
context: "Ситуация: символы выглядят идеально, но ссылка ведет на вредоносную страницу авторизации.",
options: [
{ text: "В названии латинские буквы «o» заменены визуально идентичными кириллическими буквами «о».", correct: true },
{ text: "На сервере Google упало шифрование HTTPS, поэтому антивирус перестраховывается.", correct: false },
{ text: "Ноутбук перегрелся и исказил пиксели при отображении адреса в адресной строке.", correct: false },
{ text: "Это проделки интернет-провайдера, который пытается продать свою платную защиту.", correct: false }
],
explanation: "Это омоглифическая атака. В международных доменах (IDN) символы из разных алфавитов (например, кириллическая 'а' и латинская 'a') на экране выглядят идентично, но для браузера это совершенно разные серверы: `xn--ggle-p50aa.com` вместо оригинального.",
tip: "Никогда не переходите по важным ссылкам из сообщений. Если вам нужен сервис — вбивайте адрес руками или открывайте через ранее сохраненные закладки."
},
{
id: 7,
category: "Аутентификация и криптография",
threat: "SIM-Swapping & уязвимости SS7",
question: "Сервис предлагает два варианта двухфакторной защиты: одноразовый код по СМС или код из приложения-аутентификатора. Что надежнее?",
context: "Ситуация: защита входа в личный кабинет с банковскими картами или ценной почтой.",
options: [
{ text: "СМС надежнее: телефон всегда в кармане, а сотовые операторы шифруют весь эфир.", correct: false },
{ text: "Одинаково надежно, оба способа защищают на 100% от любых атак.", correct: false },
{ text: "Приложение-аутентификатор (TOTP): СМС уязвимы к перехвату и выпуску дубликата сим-карты.", correct: true },
{ text: "Приложения опасны, потому что они передают пароли разработчикам через интернет.", correct: false }
],
explanation: "СМС-сообщения могут быть перехвачены через уязвимости протоколов сотовой связи (SS7) или получены мошенниками через поддельную доверенность у оператора (SIM-Swapping). Приложения (2FAS, Google Authenticator) генерируют коды локально по криптографическому ключу и не зависят от сотовой сети.",
tip: "Используйте приложения-аутентификаторы или аппаратные ключи FIDO2/WebAuthn (YubiKey) для всех критических аккаунтов."
}
];
// Application State
const state = {
currentIndex: 0,
userAnswers: {}, // index: { selectedOptionIndex, isCorrect }
score: 0,
isAnsweredCurrent: false
};
// DOM Elements
const elements = {
startScreen: document.getElementById('startScreen'),
quizScreen: document.getElementById('quizScreen'),
resultsScreen: document.getElementById('resultsScreen'),
startBtn: document.getElementById('startQuizBtn'),
restartQuickBtn: document.getElementById('restartQuickBtn'),
retakeBtn: document.getElementById('retakeQuizBtn'),
copyBtn: document.getElementById('copyResultsBtn'),
copyBtnText: document.getElementById('copyBtnText'),
soundToggleBtn: document.getElementById('soundToggleBtn'),
soundIconOn: document.getElementById('soundIconOn'),
soundIconOff: document.getElementById('soundIconOff'),
soundLabel: document.getElementById('soundLabel'),
// Quiz UI
currentNum: document.getElementById('currentQuestionNumber'),
totalNum: document.getElementById('totalQuestionsCount'),
liveScore: document.getElementById('liveScore'),
progressBar: document.getElementById('progressBar'),
questionDots: document.getElementById('questionDots'),
category: document.getElementById('questionCategory'),
threatTag: document.getElementById('threatTag'),
questionText: document.getElementById('questionText'),
questionContext: document.getElementById('questionContext'),
optionsContainer: document.getElementById('optionsContainer'),
explanationBox: document.getElementById('explanationContainer'),
explanationTitle: document.getElementById('explanationTitle'),
explanationBody: document.getElementById('explanationBody'),
explanationIcon: document.getElementById('explanationIcon'),
securityTip: document.getElementById('securityTip'),
nextBtn: document.getElementById('nextQuestionBtn'),
nextBtnText: document.getElementById('nextBtnText'),
// Results UI
finalScoreNumber: document.getElementById('finalScoreNumber'),
finalScorePercent: document.getElementById('finalScorePercent'),
rankTitle: document.getElementById('rankTitle'),
rankDescription: document.getElementById('rankDescription'),
answersReviewList: document.getElementById('answersReviewList')
};
// Initialize UI
elements.totalNum.textContent = questions.length;
// Sound switch toggle
elements.soundToggleBtn.addEventListener('click', () => {
SoundEngine.enabled = !SoundEngine.enabled;
if (SoundEngine.enabled) {
elements.soundIconOn.classList.remove('hidden');
elements.soundIconOff.classList.add('hidden');
elements.soundLabel.textContent = 'Звук: ВКЛ';
SoundEngine.play('click');
} else {
elements.soundIconOn.classList.add('hidden');
elements.soundIconOff.classList.remove('hidden');
elements.soundLabel.textContent = 'Звук: ВЫКЛ';
}
});
// Navigation and Start
elements.startBtn.addEventListener('click', () => {
SoundEngine.play('click');
startQuiz();
});
elements.restartQuickBtn.addEventListener('click', () => {
SoundEngine.play('click');
resetQuiz();
});
elements.retakeBtn.addEventListener('click', () => {
SoundEngine.play('click');
resetQuiz();
startQuiz();
});
function resetQuiz() {
state.currentIndex = 0;
state.userAnswers = {};
state.score = 0;
state.isAnsweredCurrent = false;
elements.resultsScreen.classList.add('hidden');
elements.quizScreen.classList.add('hidden');
elements.startScreen.classList.remove('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
}
function startQuiz() {
elements.startScreen.classList.add('hidden');
elements.resultsScreen.classList.add('hidden');
elements.quizScreen.classList.remove('hidden');
renderNavigationDots();
loadQuestion(0);
window.scrollTo({ top: 0, behavior: 'smooth' });
}
// Render Navigation Dots
function renderNavigationDots() {
elements.questionDots.innerHTML = '';
questions.forEach((_, idx) => {
const dot = document.createElement('button');
dot.type = 'button';
dot.className = `w-7 h-2.5 rounded-full transition-all duration-300 font-mono text-[10px] flex items-center justify-center ${
idx === state.currentIndex
? 'bg-cyan-400 w-10 shadow-sm shadow-cyan-400/50'
: state.userAnswers[idx]
? (state.userAnswers[idx].isCorrect ? 'bg-emerald-500/60' : 'bg-rose-500/60')
: 'bg-white/10'
}`;
dot.title = `Вопрос ${idx + 1}`;
dot.addEventListener('click', () => {
if (state.userAnswers[idx] !== undefined || idx <= Object.keys(state.userAnswers).length) {
SoundEngine.play('click');
loadQuestion(idx);
}
});
elements.questionDots.appendChild(dot);
});
}
function loadQuestion(index) {
state.currentIndex = index;
const q = questions[index];
const isAlreadyAnswered = state.userAnswers[index] !== undefined;
state.isAnsweredCurrent = isAlreadyAnswered;
// Update counters & progress bar
elements.currentNum.textContent = index + 1;
const progressPercent = Math.round(((index + 1) / questions.length) * 100);
elements.progressBar.style.width = `${progressPercent}%`;
elements.liveScore.textContent = state.score;
// Update Text
elements.category.textContent = q.category;
elements.threatTag.textContent = q.threat;
elements.questionText.textContent = q.question;
elements.questionContext.textContent = q.context;
elements.securityTip.textContent = `Совет: ${q.tip}`;
// Render Options
elements.optionsContainer.innerHTML = '';
const letters = ['А', 'Б', 'В', 'Г'];
q.options.forEach((opt, optIdx) => {
const btn = document.createElement('button');
btn.type = 'button';
btn.disabled = isAlreadyAnswered;
let baseClasses = "option-btn w-full text-left p-4 sm:p-4.5 rounded-2xl glass-card border border-white/10 flex items-start space-x-3.5 relative overflow-hidden group";
if (isAlreadyAnswered) {
const userChoice = state.userAnswers[index].selectedOptionIndex;
if (opt.correct) {
baseClasses = "w-full text-left p-4 sm:p-4.5 rounded-2xl bg-emerald-950/40 border-2 border-emerald-500/80 shadow-lg shadow-emerald-500/10 flex items-start space-x-3.5";
} else if (userChoice === optIdx && !opt.correct) {
baseClasses = "w-full text-left p-4 sm:p-4.5 rounded-2xl bg-rose-950/40 border-2 border-rose-500/80 shadow-lg shadow-rose-500/10 flex items-start space-x-3.5";
} else {
baseClasses = "w-full text-left p-4 sm:p-4.5 rounded-2xl bg-cyber-850/40 border border-white/5 opacity-50 flex items-start space-x-3.5";
}
}
btn.className = baseClasses;
// Badge Letter / Icon
let badgeHtml = `<span class="w-7 h-7 rounded-xl font-mono text-xs font-bold flex items-center justify-center flex-shrink-0 mt-0.5 ${
isAlreadyAnswered && opt.correct
? 'bg-emerald-500 text-black font-extrabold'
: isAlreadyAnswered && state.userAnswers[index]?.selectedOptionIndex === optIdx
? 'bg-rose-500 text-white font-extrabold'
: 'bg-white/5 text-slate-300 border border-white/10 group-hover:border-cyan-400 group-hover:text-cyan-300'
}">${letters[optIdx]}</span>`;
btn.innerHTML = `
${badgeHtml}
<div class="flex-1 text-xs sm:text-sm font-medium leading-relaxed ${
isAlreadyAnswered && opt.correct ? 'text-emerald-200' : 'text-slate-200'
}">
${opt.text}
</div>
`;
if (!isAlreadyAnswered) {
btn.addEventListener('click', () => handleOptionSelection(index, optIdx));
}
elements.optionsContainer.appendChild(btn);
});
// Feedback Box Handling
if (isAlreadyAnswered) {
showFeedback(index, state.userAnswers[index].isCorrect);
elements.nextBtn.classList.remove('hidden');
elements.nextBtn.classList.add('inline-flex');
elements.nextBtnText.textContent = index === questions.length - 1 ? 'Посмотреть результаты' : 'Следующий вопрос';
} else {
elements.explanationBox.classList.add('hidden');
elements.nextBtn.classList.add('hidden');
elements.nextBtn.classList.remove('inline-flex');
}
renderNavigationDots();
}
// Option selection logic
function handleOptionSelection(qIndex, selectedOptIndex) {
const q = questions[qIndex];
const isCorrect = q.options[selectedOptIndex].correct;
if (isCorrect) {
state.score += 1;
SoundEngine.play('correct');
} else {
SoundEngine.play('wrong');
}
state.userAnswers[qIndex] = {
selectedOptionIndex: selectedOptIndex,
isCorrect: isCorrect
};
elements.liveScore.textContent = state.score;
// Re-render question to apply styling and explanation
loadQuestion(qIndex);
}
function showFeedback(qIndex, isCorrect) {
const q = questions[qIndex];
elements.explanationBox.classList.remove('hidden');
if (isCorrect) {
elements.explanationBox.className = "rounded-2xl p-4 sm:p-5 transition-all duration-300 border mb-6 bg-emerald-950/30 border-emerald-500/40 shadow-lg shadow-emerald-500/10";
elements.explanationTitle.textContent = "Абсолютно верно!";
elements.explanationTitle.className = "text-sm sm:text-base font-bold text-emerald-400";
elements.threatTag.className = "text-[11px] font-mono uppercase tracking-wider px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/30";
elements.explanationIcon.className = "w-8 h-8 rounded-xl flex-shrink-0 flex items-center justify-center mt-0.5 bg-emerald-500/20 text-emerald-400";
elements.explanationIcon.innerHTML = `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/></svg>`;
} else {
elements.explanationBox.className = "rounded-2xl p-4 sm:p-5 transition-all duration-300 border mb-6 bg-rose-950/30 border-rose-500/40 shadow-lg shadow-rose-500/10";
elements.explanationTitle.textContent = "Неверно. Здесь кроется ловушка!";
elements.explanationTitle.className = "text-sm sm:text-base font-bold text-rose-400";
elements.threatTag.className = "text-[11px] font-mono uppercase tracking-wider px-2 py-0.5 rounded bg-rose-500/20 text-rose-300 border border-rose-500/30";
elements.explanationIcon.className = "w-8 h-8 rounded-xl flex-shrink-0 flex items-center justify-center mt-0.5 bg-rose-500/20 text-rose-400";
elements.explanationIcon.innerHTML = `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M6 18L18 6M6 6l12 12"/></svg>`;
}
elements.explanationBody.textContent = q.explanation;
}
// Next Question Button Click
elements.nextBtn.addEventListener('click', () => {
SoundEngine.play('click');
if (state.currentIndex < questions.length - 1) {
loadQuestion(state.currentIndex + 1);
window.scrollTo({ top: 0, behavior: 'smooth' });
} else {
showResults();
}
});
function showResults() {
SoundEngine.play('complete');
elements.quizScreen.classList.add('hidden');
elements.resultsScreen.classList.remove('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
const total = questions.length;
const score = state.score;
const percentage = Math.round((score / total) * 100);
elements.finalScoreNumber.textContent = score;
elements.finalScorePercent.textContent = `${percentage}% верных ответов`;
// Determine Cyber Title & Description
let title = "";
let desc = "";
if (score === 7) {
title = "🛡️ Кибер-гуру (Paranoid Pro)";
desc = "Феноменальный результат! Вы отлично знаете тонкости современных атак: от BadUSB до омоглифов и SS7. Вас практически невозможно застать врасплох бытовыми трюками.";
} else if (score >= 5) {
title = "🔒 Бдительный пользователь";
desc = "Хороший уровень цифровой гигиены. Вы отлично понимаете базовые угрозы, но пара хитрых приемов (вроде атак через зарядку или забытые сим-карты) требуют внимания.";
} else if (score >= 3) {
title = "⚠️ В зоне риска";
desc = "Вы полагаетесь на интуицию, но современные киберпреступники часто бьют в неочевидные места. Ознакомьтесь с разбором ошибок ниже, чтобы закрыть эти бреши.";
} else {
title = "🎯 Легкая мишень для хакеров";
desc = "Срочно пересмотрите свои цифровые привычки! Многие действия, которые казались вам безопасными, на самом деле открывают злоумышленникам доступ к вашим деньгам и аккаунтам.";
}
elements.rankTitle.textContent = title;
elements.rankDescription.textContent = desc;
// Populate Detailed Answers Review
elements.answersReviewList.innerHTML = '';
questions.forEach((q, idx) => {
const userResp = state.userAnswers[idx];
const isCorrect = userResp ? userResp.isCorrect : false;
const userSelectedOpt = userResp !== undefined ? q.options[userResp.selectedOptionIndex] : null;
const correctOpt = q.options.find(o => o.correct);
const card = document.createElement('div');
card.className = `p-4 rounded-2xl border transition-all text-left ${
isCorrect
? 'glass-card border-emerald-500/30 bg-emerald-950/10'
: 'glass-card border-rose-500/30 bg-rose-950/10'
}`;
card.innerHTML = `
<div class="flex items-start justify-between gap-2 mb-2">
<span class="text-xs font-mono font-bold text-slate-300">№${idx + 1}. ${q.category}</span>
<span class="text-[11px] font-mono px-2 py-0.5 rounded ${
isCorrect ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30' : 'bg-rose-500/20 text-rose-300 border border-rose-500/30'
}">
${isCorrect ? 'Верно (+1)' : 'Ошибка'}
</span>
</div>
<h4 class="text-sm font-semibold text-white mb-2 leading-snug">${q.question}</h4>
<div class="space-y-1.5 text-xs mb-3">
<div class="flex items-start space-x-2">
<span class="text-slate-400 font-mono">Ваш ответ:</span>
<span class="${isCorrect ? 'text-emerald-300 font-medium' : 'text-rose-300 font-medium'}">
${userSelectedOpt ? userSelectedOpt.text : 'Не отвечено'}
</span>
</div>
${!isCorrect ? `
<div class="flex items-start space-x-2">
<span class="text-emerald-400 font-mono">Правильно:</span>
<span class="text-emerald-300 font-medium">${correctOpt.text}</span>
</div>
` : ''}
</div>
<div class="text-xs text-slate-300 border-t border-white/5 pt-2 leading-relaxed">
<span class="font-semibold text-cyan-300">Суть:</span> ${q.explanation}
</div>
`;
elements.answersReviewList.appendChild(card);
});
}
elements.copyBtn.addEventListener('click', () => {
SoundEngine.play('click');
const score = state.score;
const total = questions.length;
const title = elements.rankTitle.textContent;
const textToCopy = `🛡️ Мой результат в тесте по кибербезопасности: ${score} из ${total}!\nСтатус: ${title}\nПроверьте свою цифровую грамотность!`;
// Fallback-safe clipboard copy using legacy textarea command
const dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = textToCopy;
dummy.select();
try {
document.execCommand("copy");
elements.copyBtnText.textContent = "Скопировано в буфер!";
setTimeout(() => {
elements.copyBtnText.textContent = "Скопировать результат";
}, 2200);
} catch (err) {
elements.copyBtnText.textContent = "Не удалось скопировать";
}
document.body.removeChild(dummy);
});
</script>
</body>
</html>