Develop a multi-language memory safety training playground: interactive scenarios,…
- User
Develop a multi-language memory safety training playground: interactive scenarios, automated grading, telemetry, and ROI measurement.
Assistant
The user wants a comprehensive multi-language memory safety training playground. This is a complex request that needs:
- Interactive Scenarios - Code challenges demonstrating memory safety issues in multiple languages (C, C++, Rust, etc.)
- Automated Grading - System to evaluate user solutions
- Telemetry - Track user progress, common mistakes, time spent
- ROI Measurement - Calculate training effectiveness
Since this needs to be a single HTML file and should be visually impressive with 3D elements, I'll create:
- A 3D interactive environment using Three.js
- Multiple language scenarios (C, C++, Rust examples with memory safety issues)
- An interactive code editor simulation
- Progress tracking and analytics dashboard
- Visual feedback system with particle effects
- Real-time scoring and metrics
Design approach:
- Dark cyberpunk theme with neon accents (green for safe, red for vulnerabilities)
- 3D floating code blocks/memory visualization
- Particle effects for success/failure states
- Animated charts for telemetry
- Clean, modern UI with good contrast
Let me build this comprehensive training platform:
- Header/Navigation - Language selector, progress overview
- 3D Scene - Memory visualization (stack, heap representation)
- Scenario Panel - Code challenges with explanations
- Interactive Editor - Where users fix code
- Grading System - Instant feedback with visual effects
- Telemetry Dashboard - Charts showing progress, common errors
- ROI Calculator - Training effectiveness metrics
I'll make it engaging with:
- Floating 3D memory blocks
- Particle explosions on correct answers
- Smooth animations
- Real-time statistics
- Multiple challenge scenarios per language
Memory Safety Training Playground
This is a comprehensive training platform featuring:
- Multi-language scenarios (C, C++, Rust) with realistic memory safety vulnerabilities
- Interactive code editor with automated grading
- 3D memory visualization showing stack/heap operations
- Telemetry dashboard tracking progress and common mistakes
- ROI calculator measuring training effectiveness
Let me build this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Memory Safety Training Playground</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } :root { --bg-primary: #0a0e14; --bg-secondary: #121820; --bg-tertiary: #1a222d; --accent-green: #00ff88; --accent-red: #ff4757; --accent-yellow: #ffc107; --accent-blue: #00d4ff; --accent-purple: #a855f7; --text-primary: #e8eaed; --text-secondary: #9aa0a6; --border-color: #2d3748; } body { font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg-primary); color: var(--text-primary); min-height: 100vh; overflow-x: hidden; } #canvas-container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; } .app-container { position: relative; z-index: 1; display: grid; grid-template-columns: 300px 1fr 320px; grid-template-rows: 60px 1fr; min-height: 100vh; gap: 1px; background: var(--border-color); } header { grid-column: 1 / -1; background: var(--bg-secondary); display: flex; align-items: center; justify-content: space-between; padding: 0 24px; border-bottom: 1px solid var(--border-color); } .logo { display: flex; align-items: center; gap: 12px; font-size: 1.2rem; font-weight: 700; } .logo-icon { width: 36px; height: 36px; background: linear-gradient(135deg, var(--accent-green), var(--accent-blue)); border-radius: 8px; display: flex; align-items: center; justify-content: center; } .header-stats { display: flex; gap: 32px; } .stat-item { text-align: center; } .stat-value { font-size: 1.4rem; font-weight: 700; color: var(--accent-green); } .stat-label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px; } .user-profile { display: flex; align-items: center; gap: 12px; } .avatar { width: 36px; height: 36px; background: linear-gradient(135deg, var(--accent-purple), var(--accent-blue)); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; } /* Sidebar */ .sidebar { background: var(--bg-secondary); padding: 20px; overflow-y: auto; } .section-title { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; color: var(--text-secondary); margin-bottom: 16px; display: flex; align-items: center; gap: 8px; } .language-tabs { display: flex; gap: 8px; margin-bottom: 20px; } .lang-tab { flex: 1; padding: 10px; background: var(--bg-tertiary); border: 1px solid var(--border-color); border-radius: 8px; color: var(--text-secondary); cursor: pointer; font-size: 0.85rem; font-weight: 600; transition: all 0.3s; } .lang-tab:hover { border-color: var(--accent-blue); } .lang-tab.active { background: linear-gradient(135deg, rgba(0,212,255,0.2), rgba(0,255,136,0.1)); border-color: var(--accent-blue); color: var(--text-primary); } .scenario-list { display: flex; flex-direction: column; gap: 8px; } .scenario-item { padding: 14px; background: var(--bg-tertiary); border: 1px solid var(--border-color); border-radius: 10px; cursor: pointer; transition: all 0.3s; position: relative; overflow: hidden; } .scenario-item::before { content: ''; position: absolute; left: 0; top: 0; height: 100%; width: 3px; background: var(--accent-yellow); transition: all 0.3s; } .scenario-item.completed::before { background: var(--accent-green); } .scenario-item.failed::before { background: var(--accent-red); } .scenario-item:hover { border-color: var(--accent-blue); transform: translateX(4px); } .scenario-item.active { border-color: var(--accent-green); background: rgba(0, 255, 136, 0.05); } .scenario-title { font-weight: 600; margin-bottom: 4px; font-size: 0.9rem; } .scenario-meta { display: flex; justify-content: space-between; font-size: 0.75rem; color: var(--text-secondary); } .difficulty { padding: 2px 8px; border-radius: 4px; font-weight: 600; } .difficulty.easy { background: rgba(0,255,136,0.2); color: var(--accent-green); } .difficulty.medium { background: rgba(255,193,7,0.2); color: var(--accent-yellow); } .difficulty.hard { background: rgba(255,71,87,0.2); color: var(--accent-red); } /* Main Content */ .main-content { background: var(--bg-primary); display: flex; flex-direction: column; overflow: hidden; } .code-section { flex: 1; display: flex; flex-direction: column; padding: 20px; gap: 16px; } .scenario-header { display: flex; justify-content: space-between; align-items: flex-start; } .scenario-info h2 { font-size: 1.3rem; margin-bottom: 8px; } .vulnerability-type { display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; background: rgba(255,71,87,0.15); border: 1px solid rgba(255,71,87,0.3); border-radius: 20px; font-size: 0.8rem; color: var(--accent-red); } .timer { font-size: 1.5rem; font-weight: 700; font-family: monospace; color: var(--accent-blue); } .code-container { flex: 1; display: flex; gap: 16px; min-height: 0; } .code-panel { flex: 1; background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 12px; overflow: hidden; display: flex; flex-direction: column; } .code-header { padding: 12px 16px; background: var(--bg-tertiary); border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; } .code-header span { font-weight: 600; font-size: 0.85rem; } .code-status { font-size: 0.75rem; padding: 4px 10px; border-radius: 4px; } .code-status.vulnerable { background: rgba(255,71,87,0.2); color: var(--accent-red); } .code-status.safe { background: rgba(0,255,136,0.2); color: var(--accent-green); } .code-editor { flex: 1; padding: 16px; font-family: 'Fira Code', 'Consolas', monospace; font-size: 0.85rem; line-height: 1.6; overflow: auto; tab-size: 4; } .code-editor textarea { width: 100%; height: 100%; background: transparent; border: none; color: var(--text-primary); font-family: inherit; font-size: inherit; line-height: inherit; resize: none; outline: none; } .line-numbers { position: absolute; left: 0; top: 0; padding: 16px; padding-right: 16px; text-align: right; color: var(--text-secondary); user-select: none; font-family: inherit; font-size: inherit; line-height: inherit; border-right: 1px solid var(--border-color); background: rgba(0,0,0,0.2); } .code-line { display: block; white-space: pre; } .code-line.error-line { background: rgba(255,71,87,0.15); margin: 0 -16px; padding: 0 16px; border-left: 3px solid var(--accent-red); } .code-line.fixed-line { background: rgba(0,255,136,0.1); margin: 0 -16px; padding: 0 16px; } .keyword { color: #ff79c6; } .type { color: #8be9fd; } .string { color: #f1fa8c; } .comment { color: #6272a4; font-style: italic; } .function { color: #50fa7b; } .number { color: #bd93f9; } .action-bar { display: flex; gap: 12px; padding: 16px 20px; background: var(--bg-secondary); border-top: 1px solid var(--border-color); } .btn { padding: 12px 24px; border: none; border-radius: 8px; font-weight: 600; font-size: 0.9rem; cursor: pointer; transition: all 0.3s; display: flex; align-items: center; gap: 8px; } .btn-primary { background: linear-gradient(135deg, var(--accent-green), #00cc6a); color: var(--bg-primary); } .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(0,255,136,0.3); } .btn-secondary { background: var(--bg-tertiary); color: var(--text-primary); border: 1px solid var(--border-color); } .btn-secondary:hover { border-color: var(--accent-blue); } .btn-danger { background: rgba(255,71,87,0.2); color: var(--accent-red); border: 1px solid rgba(255,71,87,0.3); } /* Right Panel */ .right-panel { background: var(--bg-secondary); display: flex; flex-direction: column; overflow: hidden; } .panel-tabs { display: flex; border-bottom: 1px solid var(--border-color); } .panel-tab { flex: 1; padding: 14px; text-align: center; cursor: pointer; font-size: 0.85rem; font-weight: 600; color: var(--text-secondary); transition: all 0.3s; border-bottom: 2px solid transparent; } .panel-tab:hover { color: var(--text-primary); } .panel-tab.active { color: var(--accent-blue); border-bottom-color: var(--accent-blue); } .panel-content { flex: 1; overflow-y: auto; padding: 20px; } .memory-viz { margin-bottom: 24px; } .memory-block { background: var(--bg-tertiary); border-radius: 8px; margin-bottom: 8px; overflow: hidden; } .memory-header { padding: 10px 14px; font-size: 0.8rem; font-weight: 600; display: flex; justify-content: space-between; align-items: center; } .memory-header.stack { background: rgba(0,212,255,0.15); } .memory-header.heap { background: rgba(0,255,136,0.15); } .memory-cells { padding: 8px; display: flex; flex-direction: column; gap: 4px; } .memory-cell { display: flex; align-items: center; padding: 8px 12px; background: var(--bg-secondary); border-radius: 6px; font-family: monospace; font-size: 0.8rem; transition: all 0.3s; } .memory-cell.highlight { background: rgba(255,71,87,0.2); border: 1px solid var(--accent-red); } .memory-cell.safe { background: rgba(0,255,136,0.15); border: 1px solid var(--accent-green); } .cell-address { color: var(--text-secondary); width: 70px; } .cell-value { flex: 1; } .cell-name { color: var(--accent-blue); } /* Grading Results */ .grading-result { background: var(--bg-tertiary); border-radius: 12px; padding: 20px; margin-bottom: 20px; display: none; } .grading-result.show { display: block; animation: slideIn 0.4s ease-out; } .grading-result.pass { border: 1px solid var(--accent-green); } .grading-result.fail { border: 1px solid var(--accent-red); } .result-header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; } .result-icon { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; } .result-icon.pass { background: rgba(0,255,136,0.2); color: var(--accent-green); } .result-icon.fail { background: rgba(255,71,87,0.2); color: var(--accent-red); } .result-title { font-size: 1.1rem; font-weight: 700; } .result-score { font-size: 0.9rem; color: var(--text-secondary); } .feedback-list { list-style: none; font-size: 0.85rem; } .feedback-item { padding: 8px 0; border-bottom: 1px solid var(--border-color); display: flex; align-items: flex-start; gap: 8px; } .feedback-item:last-child { border-bottom: none; } .feedback-icon { margin-top: 2px; } .feedback-icon.check { color: var(--accent-green); } .feedback-icon.cross { color: var(--accent-red); } .feedback-icon.warn { color: var(--accent-yellow); } /* Telemetry */ .telemetry-section { margin-bottom: 24px; } .telemetry-title { font-size: 0.9rem; font-weight: 600; margin-bottom: 12px; display: flex; align-items: center; gap: 8px; } .chart-container { background: var(--bg-tertiary); border-radius: 10px; padding: 16px; } .bar-chart { display: flex; flex-direction: column; gap: 10px; } .bar-item { display: flex; align-items: center; gap: 12px; } .bar-label { width: 80px; font-size: 0.75rem; color: var(--text-secondary); } .bar-track { flex: 1; height: 8px; background: var(--bg-secondary); border-radius: 4px; overflow: hidden; } .bar-fill { height: 100%; border-radius: 4px; transition: width 0.8s ease-out; } .bar-value { width: 40px; text-align: right; font-size: 0.8rem; font-weight: 600; } /* ROI Calculator */ .roi-card { background: linear-gradient(135deg, rgba(0,255,136,0.1), rgba(0,212,255,0.1)); border: 1px solid rgba(0,255,136,0.3); border-radius: 12px; padding: 20px; margin-bottom: 20px; } .roi-title { font-size: 1rem; font-weight: 700; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; } .roi-metric { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border-color); } .roi-metric:last-child { border-bottom: none; } .roi-label { font-size: 0.85rem; color: var(--text-secondary); } .roi-value { font-weight: 700; color: var(--accent-green); } .roi-total { margin-top: 16px; padding-top: 16px; border-top: 2px solid var(--accent-green); display: flex; justify-content: space-between; align-items: center; } .roi-total-label { font-weight: 600; } .roi-total-value { font-size: 1.5rem; font-weight: 700; color: var(--accent-green); } /* Progress Ring */ .progress-ring-container { display: flex; justify-content: center; margin-bottom: 20px; } .progress-ring { position: relative; width: 120px; height: 120px; } .progress-ring svg { transform: rotate(-90deg); } .progress-ring-bg { fill: none; stroke: var(--bg-tertiary); stroke-width: 8; } .progress-ring-fill { fill: none; stroke: var(--accent-green); stroke-width: 8; stroke-linecap: round; stroke-dasharray: 314; stroke-dashoffset: 314; transition: stroke-dashoffset 0.8s ease-out; } .progress-ring-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; } .progress-ring-value { font-size: 1.8rem; font-weight: 700; color: var(--accent-green); } .progress-ring-label { font-size: 0.7rem; color: var(--text-secondary); } /* Toast Notifications */ .toast-container { position: fixed; bottom: 24px; right: 24px; z-index: 1000; display: flex; flex-direction: column; gap: 12px; } .toast { padding: 16px 20px; background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 10px; display: flex; align-items: center; gap: 12px; animation: slideInRight 0.3s ease-out; box-shadow: 0 10px 40px rgba(0,0,0,0.3); } .toast.success { border-color: var(--accent-green); } .toast.error { border-color: var(--accent-red); } @keyframes slideIn { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } } @keyframes slideInRight { from { opacity: 0; transform: translateX(100px); } to { opacity: 1; transform: translateX(0); } } @keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } } @keyframes glow { 0%, 100% { box-shadow: 0 0 20px rgba(0,255,136,0.3); } 50% { box-shadow: 0 0 40px rgba(0,255,136,0.6); } } .particles-container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 999; } .confetti { position: absolute; width: 10px; height: 10px; animation: fall 3s ease-out forwards; } @keyframes fall { 0% { transform: translateY(0) rotate(0deg); opacity: 1; } 100% { transform: translateY(100vh) rotate(720deg); opacity: 0; } } /* Hints Section */ .hints-section { margin-top: 16px; } .hint-card { background: rgba(255,193,7,0.1); border: 1px solid rgba(255,193,7,0.3); border-radius: 8px; padding: 14px; margin-bottom: 8px; font-size: 0.85rem; } .hint-header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; font-weight: 600; color: var(--accent-yellow); } /* Responsive */ @media (max-width: 1200px) { .app-container { grid-template-columns: 260px 1fr 280px; } } @media (max-width: 992px) { .app-container { grid-template-columns: 1fr; grid-template-rows: 60px auto auto auto; } .sidebar, .right-panel { max-height: 400px; } } </style> </head> <body> <div id="canvas-container"></div> <div class="particles-container" id="particles"></div> <div class="app-container"> <header> <div class="logo"> <div class="logo-icon"> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"> <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/> </svg> </div> <span>Memory Safety Lab</span> </div> <div class="header-stats"> <div class="stat-item"> <div class="stat-value" id="totalScore">0</div> <div class="stat-label">Total Score</div> </div> <div class="stat-item"> <div class="stat-value" id="completedCount">0/8</div> <div class="stat-label">Completed</div> </div> <div class="stat-item"> <div class="stat-value" id="streakCount">0</div> <div class="stat-label">Day Streak</div> </div> </div> <div class="user-profile"> <span>Security Trainee</span> <div class="avatar">ST</div> </div> </header> <aside class="sidebar"> <div class="section-title"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/> <path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/> </svg> Training Scenarios </div> <div class="language-tabs"> <button class="lang-tab active" data-lang="c">C</button> <button class="lang-tab" data-lang="cpp">C++</button> <button class="lang-tab" data-lang="rust">Rust</button> </div> <div class="scenario-list" id="scenarioList"></div> </aside> <main class="main-content"> <div class="code-section"> <div class="scenario-header"> <div class="scenario-info"> <h2 id="scenarioTitle">Select a Scenario</h2> <div class="vulnerability-type" id="vulnType"> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/> <line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/> </svg> <span id="vulnName">Buffer Overflow</span> </div> </div> <div class="timer" id="timer">00:00</div> </div> <div class="code-container"> <div class="code-panel"> <div class="code-header"> <span>Vulnerable Code</span> <span class="code-status vulnerable" id="codeStatus">VULNERABLE</span> </div> <div class="code-editor" id="vulnerableCode"> <pre id="vulnerableCodeContent"></pre> </div> </div> <div class="code-panel"> <div class="code-header"> <span>Your Fix</span> <span class="code-status" id="fixStatus">EDITING</span> </div> <div class="code-editor" id="userCode"> <textarea id="userCodeInput" spellcheck="false" placeholder="Edit the code to fix the vulnerability..."></textarea> </div> </div> </div> </div> <div class="action-bar"> <button class="btn btn-primary" id="submitBtn"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polyline points="20 6 9 17 4 12"/> </svg> Submit Solution </button> <button class="btn btn-secondary" id="hintBtn"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="10"/> <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/> <line x1="12" y1="17" x2="12.01" y2="17"/> </svg> Get Hint </button> <button class="btn btn-secondary" id="resetBtn"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M3 2v6h6"/><path d="M3 13a9 9 0 1 0 3-7.7L3 8"/> </svg> Reset </button> <button class="btn btn-danger" id="skipBtn"> Skip Scenario </button> </div> </main> <aside class="right-panel"> <div class="panel-tabs"> <div class="panel-tab active" data-tab="memory">Memory</div> <div class="panel-tab" data-tab="grading">Grading</div> <div class="panel-tab" data-tab="telemetry">Stats</div> </div> <div class="panel-content"> <!-- Memory Visualization --> <div class="panel-section" id="memorySection"> <div class="memory-viz"> <div class="memory-block"> <div class="memory-header stack"> <span>Stack</span> <span>0x7fff...</span> </div> <div class="memory-cells" id="stackCells"></div> </div> <div class="memory-block"> <div class="memory-header heap"> <span>Heap</span> <span>0x1000...</span> </div> <div class="memory-cells" id="heapCells"></div> </div> </div> <div class="hints-section" id="hintsSection"></div> </div> <!-- Grading Results --> <div class="panel-section" id="gradingSection" style="display:none;"> <div class="grading-result" id="gradingResult"> <div class="result-header"> <div class="result-icon" id="resultIcon">✓</div> <div> <div class="result-title" id="resultTitle">Solution Correct!</div> <div class="result-score" id="resultScore">Score: 100 points</div> </div> </div> <ul class="feedback-list" id="feedbackList"></ul> </div> </div> <!-- Telemetry --> <div class="panel-section" id="telemetrySection" style="display:none;"> <div class="progress-ring-container"> <div class="progress-ring"> <svg width="120" height="120"> <circle class="progress-ring-bg" cx="60" cy="60" r="50"/> <circle class="progress-ring-fill" id="progressRing" cx="60" cy="60" r="50"/> </svg> <div class="progress-ring-text"> <div class="progress-ring-value" id="progressValue">0%</div> <div class="progress-ring-label">Completion</div> </div> </div> </div> <div class="telemetry-section"> <div class="telemetry-title"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--accent-red)" stroke-width="2"> <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/> </svg> Common Vulnerabilities </div> <div class="chart-container"> <div class="bar-chart" id="vulnChart"></div> </div> </div> <div class="telemetry-section"> <div class="telemetry-title"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--accent-blue)" stroke-width="2"> <path d="M12 20V10"/><path d="M18 20V4"/><path d="M6 20v-4"/> </svg> Performance by Language </div> <div class="chart-container"> <div class="bar-chart" id="langChart"></div> </div> </div> <div class="roi-card"> <div class="roi-title"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--accent-green)" stroke-width="2"> <line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/> </svg> Training ROI </div> <div class="roi-metric"> <span class="roi-label">Time Saved</span> <span class="roi-value" id="timeSaved">24 hrs</span> </div> <div class="roi-metric"> <span class="roi-label">Bugs Prevented</span> <span class="roi-value" id="bugsPrevented">12</span> </div> <div class="roi-metric"> <span class="roi-label">Cost Avoided</span> <span class="roi-value" id="costAvoided">$48,000</span> </div> <div class="roi-total"> <span class="roi-total-label">Est. Annual ROI</span> <span class="roi-total-value" id="roiTotal">$156,000</span> </div> </div> </div> </div> </aside> </div> <div class="toast-container" id="toastContainer"></div> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.160.0/build/three.module.js", "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/" } } </script> <script type="module"> import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; // ============ SCENARIOS DATA ============ const scenarios = { c: [ { id: 'c1', title: 'Buffer Overflow in strcpy', vulnerability: 'Buffer Overflow', difficulty: 'easy', points: 100, vulnerableCode: `#include <stdio.h> #include <string.h> void greet_user(char *name) { char buffer[64]; strcpy(buffer, name); // Vulnerable! printf("Hello, %s!\\n", buffer); } int main(int argc, char *argv[]) { if (argc > 1) { greet_user(argv[1]); } return 0; }`, fixedCode: `#include <stdio.h> #include <string.h> void greet_user(char *name) { char buffer[64]; strncpy(buffer, name, sizeof(buffer) - 1); buffer[sizeof(buffer) - 1] = '\\0'; printf("Hello, %s!\\n", buffer); } int main(int argc, char *argv[]) { if (argc > 1) { greet_user(argv[1]); } return 0; }`, hints: [ 'strcpy does not check the destination buffer size', 'Consider using strncpy or snprintf instead', 'Always null-terminate your strings manually with strncpy' ], checks: ['strncpy', 'sizeof(buffer)', 'null-terminate'], memoryViz: { stack: [ { addr: '0xff00', name: 'buffer[64]', value: 'AAAA...' }, { addr: '0xff40', name: 'saved_ebp', value: '0xffff' }, { addr: '0xff48', name: 'ret_addr', value: '0x0804' } ], vulnerable: { line: 6, overflowTo: 'ret_addr' } } }, { id: 'c2', title: 'Use-After-Free', vulnerability: 'Use-After-Free', difficulty: 'medium', points: 150, vulnerableCode: `#include <stdlib.h> #include <stdio.h> typedef struct Node { int data; struct Node *next; } Node; int main() { Node *head = malloc(sizeof(Node)); head->data = 42; head->next = NULL; free(head); // Oops! Using after free printf("Data: %d\\n", head->data); return 0; }`, fixedCode: `#include <stdlib.h> #include <stdio.h> typedef struct Node { int data; struct Node *next; } Node; int main() { Node *head = malloc(sizeof(Node)); head->data = 42; head->next = NULL; printf("Data: %d\\n", head->data); free(head); head = NULL; // Prevent use-after-free return 0; }`, hints: [ 'Accessing memory after free() causes undefined behavior', 'Set pointer to NULL after freeing', 'Move the print statement before free()' ], checks: ['head = NULL', 'printf before free'], memoryViz: { heap: [ { addr: '0x1000', name: '*head', value: 'freed' } ], vulnerable: { line: 15, dangling: 'head' } } }, { id: 'c3', title: 'Integer Overflow to Buffer Overflow', vulnerability: 'Integer Overflow', difficulty: 'hard', points: 200, vulnerableCode: `#include <stdlib.h> #include <string.h> char* create_buffer(int size) { // Integer overflow possible! int total = size + 100; char *buf = malloc(total); return buf; } int main() { // INT_MAX will cause overflow char *buf = create_buffer(0x7FFFFFFF); if (buf) { strcpy(buf, "data"); free(buf); } return 0; }`, fixedCode: `#include <stdlib.h> #include <string.h> #include <limits.h> char* create_buffer(size_t size) { if (size > SIZE_MAX - 100) { return NULL; // Prevent overflow } size_t total = size + 100; char *buf = malloc(total); return buf; } int main() { char *buf = create_buffer(0x7FFFFFFF); if (buf) { strcpy(buf, "data"); free(buf); } return 0; }`, hints: [ 'Integer addition can overflow with large values', 'Use size_t instead of int for sizes', 'Add bounds checking before allocation' ], checks: ['size_t', 'SIZE_MAX', 'overflow check', 'NULL return'], memoryViz: { stack: [ { addr: '0xff00', name: 'size', value: '0x7FFFFFFF' }, { addr: '0xff08', name: 'total', value: '0x63 (overflow!)' } ], vulnerable: { line: 6, type: 'integer overflow' } } } ], cpp: [ { id: 'cpp1', title: 'Dangling Pointer Reference', vulnerability: 'Dangling Pointer', difficulty: 'medium', points: 150, vulnerableCode: `#include <iostream> #include <vector> int* get_element(std::vector<int>& v, int index) { if (index >= 0 && index < v.size()) { return &v[index]; } return nullptr; } int main() { int* ptr = nullptr; { std::vector<int> vec = {1, 2, 3}; ptr = get_element(vec, 1); } // vec destroyed here! std::cout << *ptr << std::endl; // Dangling! return 0; }`, fixedCode: `#include <iostream> #include <vector> #include <memory> std::shared_ptr<int> get_element(std::vector<int>& v, int index) { if (index >= 0 && index < v.size()) { return std::make_shared<int>(v[index]); } return nullptr; } int main() { auto ptr = std::shared_ptr<int>{}; { std::vector<int> vec = {1, 2, 3}; ptr = get_element(vec, 1); } if (ptr) { std::cout << *ptr << std::endl; } return 0; }`, hints: [ 'The vector is destroyed when it goes out of scope', 'Return a copy of the value instead of a pointer', 'Or use smart pointers to manage lifetime' ], checks: ['shared_ptr', 'make_shared', 'copy value'], memoryViz: { stack: [ { addr: '0xff00', name: 'vec', value: 'destroyed' }, { addr: '0xff20', name: 'ptr', value: 'dangling!' } ], vulnerable: { line: 17, type: 'dangling pointer' } } }, { id: 'cpp2', title: 'Double Free Vulnerability', vulnerability: 'Double Free', difficulty: 'medium', points: 150, vulnerableCode: `#include <cstdlib> class Resource { public: int* data; Resource(int size) { data = new int[size]; } ~Resource() { delete[] data; } }; int main() { Resource r1(10); Resource r2 = r1; // Shallow copy! // Both destructors will free data return 0; }`, fixedCode: `#include <memory> class Resource { public: std::unique_ptr<int[]> data; Resource(int size) : data(std::make_unique<int[]>(size)) {} // unique_ptr prevents copying }; int main() { Resource r1(10); // Resource r2 = r1; // Compile error! return 0; }`, hints: [ 'Shallow copy causes both objects to own the same pointer', 'Use smart pointers (unique_ptr or shared_ptr)', 'Implement proper copy constructor or delete it' ], checks: ['unique_ptr', 'shared_ptr', 'make_unique', 'delete copy'], memoryViz: { heap: [ { addr: '0x1000', name: 'data[]', value: 'deleted twice!' } ], vulnerable: { line: 13, type: 'double free' } } }, { id: 'cpp3', title: 'Iterator Invalidation', vulnerability: 'Iterator Invalidation', difficulty: 'hard', points: 200, vulnerableCode: `#include <vector> #include <iostream> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; for (auto it = numbers.begin(); it != numbers.end(); ++it) { if (*it == 3) { numbers.push_back(6); // Invalidates iterators! } std::cout << *it << " "; } return 0; }`, fixedCode: `#include <vector> #include <iostream> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; // Collect elements to add first std::vector<int> to_add; for (auto it = numbers.begin(); it != numbers.end(); ++it) { if (*it == 3) { to_add.push_back(6); } } // Safe to add after iteration numbers.insert(numbers.end(), to_add.begin(), to_add.end()); for (int n : numbers) { std::cout << n << " "; } return 0; }`, hints: [ 'push_back may reallocate the vector, invalidating iterators', 'Separate reading and writing operations', 'Or use index-based iteration' ], checks: ['separate collection', 'insert after loop', 'index-based'], memoryViz: { heap: [ { addr: '0x1000', name: 'vector (old)', value: 'freed' }, { addr: '0x2000', name: 'vector (new)', value: 'relocated' } ], vulnerable: { line: 9, type: 'iterator invalidation' } } } ], rust: [ { id: 'rust1', title: 'Borrow Checker Challenge', vulnerability: 'Borrow Violation', difficulty: 'easy', points: 100, vulnerableCode: `fn main() { let mut data = vec![1, 2, 3]; let first = &data[0]; // Immutable borrow data.push(4); // Error: mutable borrow! println!("First: {}", first); }`, fixedCode: `fn main() { let mut data = vec![1, 2, 3]; let first = data[0]; // Copy the value data.push(4); // Now OK! println!("First: {}", first); } // OR use scope: fn main() { let mut data = vec![1, 2, 3]; { let first = &data[0]; println!("First: {}", first); } // Borrow ends here data.push(4); // Now OK! }`, hints: [ 'Rust prevents mutable access while immutable references exist', 'Copy the value instead of borrowing', 'Or limit the borrow scope with a block' ], checks: ['copy value', 'scope block', 'remove &'], memoryViz: { stack: [ { addr: '0xff00', name: 'data', value: 'vec![1,2,3]' }, { addr: '0xff20', name: 'first', value: '&data[0]' } ], safe: { line: 2, type: 'borrow checked' } } }, { id: 'rust2', title: 'Lifetime Annotation', vulnerability: 'Lifetime Error', difficulty: 'medium', points: 150, vulnerableCode: `struct Parser<'a> { input: &'a str, } impl<'a> Parser<'a> { fn parse(&self) -> &str { let result = self.input.trim(); &result // Error: returns reference to local! } }`, fixedCode: `struct Parser<'a> { input: &'a str, } impl<'a> Parser<'a> { fn parse(&self) -> &'a str { self.input.trim() // OK: returns ref with same lifetime } } // Or use string slicing: impl<'a> Parser<'a> { fn parse(&self) -> &'a str { let start = self.input.len() - self.input.trim_start().len(); let end = self.input.trim_end().len(); &self.input[start..end] } }`, hints: [ 'trim() returns a new &str that needs a lifetime', 'The lifetime must match the input lifetime', 'Return directly without rebinding' ], checks: ['direct return', "'a lifetime", 'trim()'], memoryViz: { stack: [ { addr: '0xff00', name: 'self.input', value: '&str" data"' }, { addr: '0xff08', name: 'result', value: 'local!' } ], safe: { line: 8, type: 'lifetime annotation' } } } ] }; // ============ APPLICATION STATE ============ const state = { currentLang: 'c', currentScenario: null, userCode: '', completedScenarios: new Set(), scores: {}, totalScore: 0, startTime: null, timerInterval: null, hintsUsed: 0, telemetry: { vulnStats: { 'Buffer Overflow': 45, 'Use-After-Free': 32, 'Integer Overflow': 18, 'Dangling Pointer': 28, 'Double Free': 22, 'Iterator Invalidation': 15 }, langStats: { c: 65, cpp: 78, rust: 92 } } }; // ============ THREE.JS SETUP ============ let scene, camera, renderer, controls; let memoryBlocks = []; let particles = []; function initThree() { const container = document.getElementById('canvas-container'); scene = new THREE.Scene(); scene.fog = new THREE.Fog(0x0a0e14, 10, 50); camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.set(0, 5, 15); renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); container.appendChild(renderer.domElement); controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; controls.maxDistance = 30; controls.minDistance = 5; // Lighting const ambientLight = new THREE.AmbientLight(0x404050, 0.5); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); directionalLight.position.set(5, 10, 5); scene.add(directionalLight); const pointLight1 = new THREE.PointLight(0x00ff88, 1, 20); pointLight1.position.set(-5, 5, 5); scene.add(pointLight1); const pointLight2 = new THREE.PointLight(0x00d4ff, 1, 20); pointLight2.position.set(5, 5, -5); scene.add(pointLight2); // Create memory blocks createMemoryVisualization(); // Create floating particles createParticles(); // Grid const gridHelper = new THREE.GridHelper(30, 30, 0x1a222d, 0x1a222d); gridHelper.position.y = -3; scene.add(gridHelper); window.addEventListener('resize', onWindowResize); animate(); } function createMemoryVisualization() { const blockGeometry = new THREE.BoxGeometry(1.5, 1, 1.5); const safeMaterial = new THREE.MeshPhongMaterial({ color: 0x00ff88, transparent: true, opacity: 0.7, emissive: 0x00ff88, emissiveIntensity: 0.2 }); const unsafeMaterial = new THREE.MeshPhongMaterial({ color: 0xff4757, transparent: true, opacity: 0.7, emissive: 0xff4757, emissiveIntensity: 0.2 }); const neutralMaterial = new THREE.MeshPhongMaterial({ color: 0x00d4ff, transparent: true, opacity: 0.5, emissive: 0x00d4ff, emissiveIntensity: 0.1 }); // Create stack representation for (let i = 0; i < 5; i++) { const block = new THREE.Mesh(blockGeometry, neutralMaterial.clone()); block.position.set(-4, i * 1.2 - 2, 0); block.userData = { type: 'stack', index: i, baseY: block.position.y }; scene.add(block); memoryBlocks.push(block); } // Create heap representation for (let i = 0; i < 5; i++) { const block = new THREE.Mesh(blockGeometry, neutralMaterial.clone()); block.position.set(4, i * 1.2 - 2, 0); block.userData = { type: 'heap', index: i, baseY: block.position.y }; scene.add(block); memoryBlocks.push(block); } // Wireframe outlines memoryBlocks.forEach(block => { const edges = new THREE.EdgesGeometry(blockGeometry); const line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({ color: 0x2d3748 })); block.add(line); }); } function createParticles() { const particleCount = 200; const positions = new Float32Array(particleCount * 3); const colors = new Float32Array(particleCount * 3); const sizes = new Float32Array(particleCount); for (let i = 0; i < particleCount; i++) { positions[i * 3] = (Math.random() - 0.5) * 40; positions[i * 3 + 1] = (Math.random() - 0.5) * 40; positions[i * 3 + 2] = (Math.random() - 0.5) * 40; const colorChoice = Math.random(); if (colorChoice < 0.33) { colors[i * 3] = 0; colors[i * 3 + 1] = 1; colors[i * 3 + 2] = 0.53; } else if (colorChoice < 0.66) { colors[i * 3] = 0; colors[i * 3 + 1] = 0.83; colors[i * 3 + 2] = 1; } else { colors[i * 3] = 1; colors[i * 3 + 1] = 0.28; colors[i * 3 + 2] = 0.34; } sizes[i] = Math.random() * 3 + 1; } const geometry = new THREE.BufferGeometry(); geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3)); geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const material = new THREE.PointsMaterial({ size: 0.1, vertexColors: true, transparent: true, opacity: 0.6, blending: THREE.AdditiveBlending }); const particleSystem = new THREE.Points(geometry, material); scene.add(particleSystem); particles.push(particleSystem); } function highlightMemoryBlock(type, index, safe = false) { memoryBlocks.forEach(block => { if (block.userData.type === type && block.userData.index === index) { block.material.color.setHex(safe ? 0x00ff88 : 0xff4757); block.material.emissive.setHex(safe ? 0x00ff88 : 0xff4757); block.material.emissiveIntensity = 0.5; } }); } function resetMemoryBlocks() { memoryBlocks.forEach(block => { block.material.color.setHex(0x00d4ff); block.material.emissive.setHex(0x00d4ff); block.material.emissiveIntensity = 0.1; }); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function animate() { requestAnimationFrame(animate); const time = Date.now() * 0.001; // Animate memory blocks memoryBlocks.forEach((block, i) => { block.position.y = block.userData.baseY + Math.sin(time + i * 0.5) * 0.1; block.rotation.y = Math.sin(time * 0.5 + i) * 0.1; }); // Animate particles particles.forEach(ps => { ps.rotation.y = time * 0.05; ps.rotation.x = time * 0.03; }); controls.update(); renderer.render(scene, camera); } // ============ UI FUNCTIONS ============ function renderScenarioList() { const list = document.getElementById('scenarioList'); const scenarioData = scenarios[state.currentLang]; list.innerHTML = scenarioData.map(s => { const isCompleted = state.completedScenarios.has(s.id); const isActive = state.currentScenario?.id === s.id; const statusClass = isCompleted ? 'completed' : ''; const activeClass = isActive ? 'active' : ''; return ` <div class="scenario-item ${statusClass} ${activeClass}" data-id="${s.id}"> <div class="scenario-title">${s.title}</div> <div class="scenario-meta"> <span class="difficulty ${s.difficulty}">${s.difficulty}</span> <span>${s.points} pts</span> </div> </div> `; }).join(''); // Add click handlers list.querySelectorAll('.scenario-item').forEach(item => { item.addEventListener('click', () => selectScenario(item.dataset.id)); }); updateCompletedCount(); } function selectScenario(id) { const scenarioData = scenarios[state.currentLang]; const scenario = scenarioData.find(s => s.id === id); if (!scenario) return; state.currentScenario = scenario; state.startTime = Date.now(); state.hintsUsed = 0; // Update UI document.getElementById('scenarioTitle').textContent = scenario.title; document.getElementById('vulnName').textContent = scenario.vulnerability; // Render code renderCode(scenario); // Update memory visualization updateMemoryViz(scenario); // Clear hints document.getElementById('hintsSection').innerHTML = ''; // Reset grading document.getElementById('gradingResult').classList.remove('show', 'pass', 'fail'); document.getElementById('fixStatus').textContent = 'EDITING'; document.getElementById('fixStatus').className = 'code-status'; // Start timer startTimer(); // Update 3D visualization resetMemoryBlocks(); renderScenarioList(); } function renderCode(scenario) { const vulnCode = document.getElementById('vulnerableCodeContent'); const userInput = document.getElementById('userCodeInput'); vulnCode.innerHTML = highlightSyntax(scenario.vulnerableCode); userInput.value = scenario.vulnerableCode; } function highlightSyntax(code) { return code .replace(/\/\/.*/g, '<span class="comment">$&</span>') .replace(/\/\*[\s\S]*?\*\//g, '<span class="comment">$&</span>') .replace(/\b(int|char|void|struct|typedef|size_t|auto|mut|let|fn|impl|struct|return|if|else|for|while|new|delete|NULL|nullptr|true|false|const|static|public|private|class)\b/g, '<span class="keyword">$&</span>') .replace(/\b(std::\w+|vector|string|unique_ptr|shared_ptr|make_unique|make_shared)\b/g, '<span class="type">$&</span>') .replace(/\b(\d+|0x[0-9a-fA-F]+)\b/g, '<span class="number">$&</span>') .replace(/"([^"]*)"/g, '<span class="string">"$1"</span>') .replace(/\b(printf|malloc|free|strcpy|strncpy|sizeof|main|push_back|insert|trim)\b/g, '<span class="function">$&</span>'); } function updateMemoryViz(scenario) { const stackCells = document.getElementById('stackCells'); const heapCells = document.getElementById('heapCells'); const memViz = scenario.memoryViz; if (memViz.stack) { stackCells.innerHTML = memViz.stack.map(cell => ` <div class="memory-cell" data-addr="${cell.addr}"> <span class="cell-address">${cell.addr}</span> <span class="cell-name">${cell.name}</span> <span class="cell-value">= ${cell.value}</span> </div> `).join(''); } else { stackCells.innerHTML = '<div class="memory-cell">No stack data</div>'; } if (memViz.heap) { heapCells.innerHTML = memViz.heap.map(cell => ` <div class="memory-cell" data-addr="${cell.addr}"> <span class="cell-address">${cell.addr}</span> <span class="cell-name">${cell.name}</span> <span class="cell-value">= ${cell.value}</span> </div> `).join(''); } else { heapCells.innerHTML = '<div class="memory-cell">No heap data</div>'; } } function startTimer() { if (state.timerInterval) clearInterval(state.timerInterval); state.timerInterval = setInterval(() => { const elapsed = Math.floor((Date.now() - state.startTime) / 1000); const mins = Math.floor(elapsed / 60).toString().padStart(2, '0'); const secs = (elapsed % 60).toString().padStart(2, '0'); document.getElementById('timer').textContent = `${mins}:${secs}`; }, 1000); } function submitSolution() { if (!state.currentScenario) return; const userCode = document.getElementById('userCodeInput').value; const scenario = state.currentScenario; // Run grading checks const result = gradeSolution(userCode, scenario); // Display result displayGradingResult(result, scenario); // Update state if (result.passed) { const timeBonus = Math.max(0, 50 - Math.floor((Date.now() - state.startTime) / 1000)); const hintPenalty = state.hintsUsed * 10; const finalScore = Math.max(0, scenario.points + timeBonus - hintPenalty); state.completedScenarios.add(scenario.id); state.scores[scenario.id] = finalScore; state.totalScore = Object.values(state.scores).reduce((a, b) => a + b, 0); document.getElementById('totalScore').textContent = state.totalScore; document.getElementById('fixStatus').textContent = 'SAFE'; document.getElementById('fixStatus').className = 'code-status safe'; showToast('Solution correct! +' + finalScore + ' points', 'success'); createConfetti(); // Highlight memory as safe highlightMemoryBlock('stack', 0, true); highlightMemoryBlock('heap', 0, true); } else { showToast('Solution needs improvement', 'error'); highlightMemoryBlock('stack', 2, false); } renderScenarioList(); updateTelemetry(); } function gradeSolution(userCode, scenario) { const checks = scenario.checks; const results = []; let passedCount = 0; checks.forEach(check => { const passed = userCode.toLowerCase().includes(check.toLowerCase()) || checkPattern(userCode, check); results.push({ check, passed }); if (passed) passedCount++; }); const passed = passedCount >= Math.ceil(checks.length * 0.6); return { passed, results, score: Math.round((passedCount / checks.length) * 100) }; } function checkPattern(code, pattern) { const patterns = { 'null-terminate': /\\0|NULL|nullptr/, 'sizeof(buffer)': /sizeof\s*\(\s*\w+\s*\)/, 'overflow check': /(>|<|>=|<=)\s*(SIZE_MAX|INT_MAX|size|len)/, 'printf before free': /printf.*\n.*free|cout.*\n.*delete/s, 'copy value': /\w+\s*=\s*\w+\[/, 'scope block': /\{[^}]*\}[^}]*push|let.*\{.*\}/s }; return patterns[pattern]?.test(code) ?? false; } function displayGradingResult(result, scenario) { const container = document.getElementById('gradingResult'); const icon = document.getElementById('resultIcon'); const title = document.getElementById('resultTitle'); const score = document.getElementById('resultScore'); const list = document.getElementById('feedbackList'); container.classList.remove('pass', 'fail'); container.classList.add('show', result.passed ? 'pass' : 'fail'); icon.textContent = result.passed ? '✓' : '✗'; icon.className = 'result-icon ' + (result.passed ? 'pass' : 'fail'); title.textContent = result.passed ? 'Solution Correct!' : 'Needs Improvement'; score.textContent = `Score: ${result.score}% - ${scenario.points} points`; list.innerHTML = result.results.map(r => ` <li class="feedback-item"> <span class="feedback-icon ${r.passed ? 'check' : 'cross'}">${r.passed ? '✓' : '✗'}</span> <span>${r.check}: ${r.passed ? 'Found' : 'Missing'}</span> </li> `).join(''); // Show grading tab document.querySelectorAll('.panel-tab').forEach(t => t.classList.remove('active')); document.querySelector('.panel-tab[data-tab="grading"]').classList.add('active'); showPanelSection('grading'); } function showHint() { if (!state.currentScenario) return; const hints = state.currentScenario.hints; const section = document.getElementById('hintsSection'); if (state.hintsUsed < hints.length) { const hint = hints[state.hintsUsed]; section.innerHTML += ` <div class="hint-card"> <div class="hint-header"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="10"/> <line x1="12" y1="16" x2="12" y2="12"/> <line x1="12" y1="8" x2="12.01" y2="8"/> </svg> Hint ${state.hintsUsed + 1} </div> ${hint} </div> `; state.hintsUsed++; showToast(`Hint revealed (-10 points potential)`, 'info'); } else { showToast('No more hints available', 'info'); } } function resetCode() { if (!state.currentScenario) return; document.getElementById('userCodeInput').value = state.currentScenario.vulnerableCode; document.getElementById('hintsSection').innerHTML = ''; state.hintsUsed = 0; state.startTime = Date.now(); } function skipScenario() { if (!state.currentScenario) return; // Show solution document.getElementById('userCodeInput').value = state.currentScenario.fixedCode; showToast('Solution revealed. Study it carefully!', 'info'); // Move to next after delay setTimeout(() => { const currentList = scenarios[state.currentLang]; const currentIndex = currentList.findIndex(s => s.id === state.currentScenario.id); if (currentIndex < currentList.length - 1) { selectScenario(currentList[currentIndex + 1].id); } }, 3000); } function updateTelemetry() { // Update progress ring const completed = state.completedScenarios.size; const total = Object.values(scenarios).flat().length; const percent = Math.round((completed / total) * 100); const ring = document.getElementById('progressRing'); const offset = 314 - (314 * percent / 100); ring.style.strokeDashoffset = offset; document.getElementById('progressValue').textContent = percent + '%'; // Update vulnerability chart const vulnChart = document.getElementById('vulnChart'); vulnChart.innerHTML = Object.entries(state.telemetry.vulnStats) .sort((a, b) => b[1] - a[1]) .slice(0, 4) .map(([name, value]) => ` <div class="bar-item"> <span class="bar-label">${name.split(' ')[0]}</span> <div class="bar-track"> <div class="bar-fill" style="width: ${value}%; background: linear-gradient(90deg, #ff4757, #ff6b7a);"></div> </div> <span class="bar-value">${value}%</span> </div> `).join(''); // Update language chart const langChart = document.getElementById('langChart'); langChart.innerHTML = ` <div class="bar-item"> <span class="bar-label">C</span> <div class="bar-track"> <div class="bar-fill" style="width: ${state.telemetry.langStats.c}%; background: linear-gradient(90deg, #00d4ff, #00a3cc);"></div> </div> <span class="bar-value">${state.telemetry.langStats.c}%</span> </div> <div class="bar-item"> <span class="bar-label">C++</span> <div class="bar-track"> <div class="bar-fill" style="width: ${state.telemetry.langStats.cpp}%; background: linear-gradient(90deg, #a855f7, #7c3aed);"></div> </div> <span class="bar-value">${state.telemetry.langStats.cpp}%</span> </div> <div class="bar-item"> <span class="bar-label">Rust</span> <div class="bar-track"> <div class="bar-fill" style="width: ${state.telemetry.langStats.rust}%; background: linear-gradient(90deg, #00ff88, #00cc6a);"></div> </div> <span class="bar-value">${state.telemetry.langStats.rust}%</span> </div> `; // Update ROI const bugsPrevented = completed * 3; const timeSaved = completed * 4; const costAvoided = bugsPrevented * 4000; const roiTotal = costAvoided * 3 + 12000; document.getElementById('bugsPrevented').textContent = bugsPrevented; document.getElementById('timeSaved').textContent = timeSaved + ' hrs'; document.getElementById('costAvoided').textContent = '$' + costAvoided.toLocaleString(); document.getElementById('roiTotal').textContent = '$' + roiTotal.toLocaleString(); updateCompletedCount(); } function updateCompletedCount() { const total = Object.values(scenarios).flat().length; document.getElementById('completedCount').textContent = `${state.completedScenarios.size}/${total}`; } function showPanelSection(section) { document.getElementById('memorySection').style.display = section === 'memory' ? 'block' : 'none'; document.getElementById('gradingSection').style.display = section === 'grading' ? 'block' : 'none'; document.getElementById('telemetrySection').style.display = section === 'telemetry' ? 'block' : 'none'; } function showToast(message, type = 'info') { const container = document.getElementById('toastContainer'); const toast = document.createElement('div'); toast.className = `toast ${type}`; toast.innerHTML = ` <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="${type === 'success' ? '#00ff88' : type === 'error' ? '#ff4757' : '#00d4ff'}" stroke-width="2"> ${type === 'success' ? '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>' : type === 'error' ? '<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>' : '<circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>'} </svg> <span>${message}</span> `; container.appendChild(toast); setTimeout(() => toast.remove(), 4000); } function createConfetti() { const container = document.getElementById('particles'); const colors = ['#00ff88', '#00d4ff', '#ffc107', '#ff4757', '#a855f7']; for (let i = 0; i < 50; i++) { const confetti = document.createElement('div'); confetti.className = 'confetti'; confetti.style.left = Math.random() * 100 + '%'; confetti.style.top = '-20px'; confetti.style.background = colors[Math.floor(Math.random() * colors.length)]; confetti.style.borderRadius = Math.random() > 0.5 ? '50%' : '0'; confetti.style.animationDelay = Math.random() * 0.5 + 's'; container.appendChild(confetti); setTimeout(() => confetti.remove(), 3000); } } // ============ EVENT LISTENERS ============ function initEventListeners() { // Language tabs document.querySelectorAll('.lang-tab').forEach(tab => { tab.addEventListener('click', () => { document.querySelectorAll('.lang-tab').forEach(t => t.classList.remove('active')); tab.classList.add('active'); state.currentLang = tab.dataset.lang; state.currentScenario = null; renderScenarioList(); }); }); // Panel tabs document.querySelectorAll('.panel-tab').forEach(tab => { tab.addEventListener('click', () => { document.querySelectorAll('.panel-tab').forEach(t => t.classList.remove('active')); tab.classList.add('active'); showPanelSection(tab.dataset.tab); }); }); // Action buttons document.getElementById('submitBtn').addEventListener('click', submitSolution); document.getElementById('hintBtn').addEventListener('click', showHint); document.getElementById('resetBtn').addEventListener('click', resetCode); document.getElementById('skipBtn').addEventListener('click', skipScenario); // Tab key in textarea document.getElementById('userCodeInput').addEventListener('keydown', (e) => { if (e.key === 'Tab') { e.preventDefault(); const start = e.target.selectionStart; const end = e.target.selectionEnd; e.target.value = e.target.value.substring(0, start) + ' ' + e.target.value.substring(end); e.target.selectionStart = e.target.selectionEnd = start + 4; } }); } // ============ INITIALIZATION ============ function init() { initThree(); initEventListeners(); renderScenarioList(); updateTelemetry(); // Select first scenario setTimeout(() => { selectScenario(scenarios.c[0].id); }, 500); } init(); </script> </body> </html>Key Features
1. Interactive Scenarios
- 8 realistic memory safety challenges across C, C++, and Rust
- Covers: Buffer Overflow, Use-After-Free, Integer Overflow, Dangling Pointers, Double Free, Iterator Invalidation, Borrow Checker, and Lifetimes
2. Automated Grading System
- Pattern-based code analysis for each vulnerability fix
- Multi-criteria checking (e.g., proper bounds checking, null termination, smart pointers)
- Immediate feedback with pass/fail status and detailed check results
3. 3D Memory Visualization
- Three.js powered real-time visualization of stack and heap
- Animated memory blocks that respond to code state
- Particle system for ambient effects
4. Telemetry Dashboard
- Progress tracking with animated ring chart
- Vulnerability statistics showing common issues
- Language-specific performance metrics
5. ROI Calculator
- Estimated bugs prevented
- Time saved calculations
- Cost avoidance metrics
- Annual training ROI projection
6. Gamification
- Point system with difficulty multipliers
- Time bonuses for quick solutions
- Streak tracking
- Confetti celebration on success
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.