The user wants me to create an iframe sandbox policy catalog. This is a technical request about creating a system that manages iframe sandbox policies, considering:
This is actually a great opportunity to create a visually appealing, interactive catalog/documentation system that showcases different iframe sandbox configurations with:
Let me design a sophisticated, modern interface for this. I'll avoid the typical blue-purple gradient and create something more technical/industrial feeling - maybe a dark theme with cyan/green accents (terminal-like aesthetic) or a warm amber/gold on dark (premium documentation feel).
Let me build this out.
Designing a comprehensive iframe sandbox policy catalog with an industrial/technical aesthetic. This will include policy presets, an interactive builder, postMessage contract patterns, and CSP integration — all with meaningful interactions.
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iframe Sandbox Policy Catalog</title>
<script src="https://cdn.tailwindcss.com"></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=JetBrains+Mono:wght@400;500;700&family=Space+Grotesk:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0a0c0f;
--bg-elevated: #12151a;
--bg-card: #181c23;
--fg: #e8eaed;
--fg-muted: #7a8599;
--accent: #00d4aa;
--accent-dim: rgba(0, 212, 170, 0.15);
--warning: #ff9f43;
--danger: #ff6b6b;
--border: #2a3142;
--code-bg: #0d1017;
}
* {
box-sizing: border-box;
}
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
}
.font-mono {
font-family: 'JetBrains Mono', monospace;
}
/* Background pattern */
.bg-grid {
background-image:
linear-gradient(rgba(0, 212, 170, 0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 212, 170, 0.03) 1px, transparent 1px);
background-size: 32px 32px;
}
/* Glow effects */
.glow-accent {
box-shadow: 0 0 40px rgba(0, 212, 170, 0.2), 0 0 80px rgba(0, 212, 170, 0.1);
}
/* Animations */
@keyframes fadeSlideUp {
from {
opacity: 0;
transform: translateY(24px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.animate-in {
animation: fadeSlideUp 0.6s ease-out forwards;
opacity: 0;
}
.animate-pulse-slow {
animation: pulse 3s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce) {
.animate-in {
animation: none;
opacity: 1;
}
.animate-pulse-slow {
animation: none;
}
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--fg-muted);
}
/* Focus states */
button:focus-visible,
input:focus-visible,
[tabindex]:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* Toggle switch */
.toggle-switch {
position: relative;
width: 44px;
height: 24px;
background: var(--border);
border-radius: 12px;
cursor: pointer;
transition: background 0.2s;
}
.toggle-switch.active {
background: var(--accent);
}
.toggle-switch::after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 20px;
height: 20px;
background: var(--fg);
border-radius: 50%;
transition: transform 0.2s;
}
.toggle-switch.active::after {
transform: translateX(20px);
}
/* Code block styling */
.code-block {
background: var(--code-bg);
border: 1px solid var(--border);
border-radius: 8px;
overflow-x: auto;
}
/* Card hover */
.policy-card {
transition: transform 0.2s, border-color 0.2s, box-shadow 0.2s;
}
.policy-card:hover {
transform: translateY(-4px);
border-color: var(--accent);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 0 1px var(--accent);
}
/* Security level indicators */
.security-low { color: var(--danger); }
.security-medium { color: var(--warning); }
.security-high { color: var(--accent); }
/* Tab underline */
.tab-active {
position: relative;
}
.tab-active::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
right: 0;
height: 2px;
background: var(--accent);
}
/* Noise texture overlay */
.noise-overlay::before {
content: '';
position: fixed;
inset: 0;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E");
opacity: 0.02;
pointer-events: none;
z-index: 1000;
}
</style>
</head>
<body class="bg-grid noise-overlay">
<!-- Header -->
<header class="fixed top-0 left-0 right-0 z-50 border-b border-[--border] bg-[--bg]/90 backdrop-blur-md">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between h-16">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded bg-[--accent-dim] flex items-center justify-center">
<svg class="w-5 h-5 text-[--accent]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
</svg>
</div>
<span class="font-bold text-lg">Sandbox Catalog</span>
</div>
<nav class="hidden sm:flex items-center gap-6 text-sm">
<button class="tab-btn tab-active text-[--fg] py-4" data-tab="catalog">Policies</button>
<button class="tab-btn text-[--fg-muted] hover:text-[--fg] py-4 transition-colors" data-tab="builder">Builder</button>
<button class="tab-btn text-[--fg-muted] hover:text-[--fg] py-4 transition-colors" data-tab="contracts">Contracts</button>
<button class="tab-btn text-[--fg-muted] hover:text-[--fg] py-4 transition-colors" data-tab="csp">CSP</button>
</nav>
<div class="flex items-center gap-2">
<span class="text-xs text-[--fg-muted] hidden sm:inline">v2.1.0</span>
<a href="#" class="p-2 rounded-lg hover:bg-[--bg-card] transition-colors" aria-label="GitHub">
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/>
</svg>
</a>
</div>
</div>
</div>
</header>
<main class="pt-16">
<!-- Catalog Section -->
<section id="catalog-section" class="tab-content min-h-screen py-12">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<!-- Hero -->
<div class="text-center mb-16 animate-in">
<div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[--accent-dim] text-[--accent] text-sm mb-6">
<span class="w-2 h-2 rounded-full bg-[--accent] animate-pulse-slow"></span>
Production-ready policies
</div>
<h1 class="text-4xl sm:text-5xl lg:text-6xl font-bold mb-4 tracking-tight">
Iframe Sandbox<br/>
<span class="text-[--accent]">Policy Catalog</span>
</h1>
<p class="text-[--fg-muted] text-lg max-w-2xl mx-auto">
Pre-configured security policies balancing integration flexibility with isolation guarantees.
Click any policy to copy its configuration.
</p>
</div>
<!-- Filters -->
<div class="flex flex-wrap items-center gap-3 mb-8 animate-in" style="animation-delay: 0.1s">
<span class="text-sm text-[--fg-muted]">Filter by use case:</span>
<button class="filter-btn active px-3 py-1.5 rounded-full text-sm bg-[--accent] text-[--bg] font-medium transition-all" data-filter="all">All</button>
<button class="filter-btn px-3 py-1.5 rounded-full text-sm bg-[--bg-card] text-[--fg-muted] hover:text-[--fg] border border-[--border] transition-all" data-filter="embed">Embeds</button>
<button class="filter-btn px-3 py-1.5 rounded-full text-sm bg-[--bg-card] text-[--fg-muted] hover:text-[--fg] border border-[--border] transition-all" data-filter="widget">Widgets</button>
<button class="filter-btn px-3 py-1.5 rounded-full text-sm bg-[--bg-card] text-[--fg-muted] hover:text-[--fg] border border-[--border] transition-all" data-filter="app">Full Apps</button>
<button class="filter-btn px-3 py-1.5 rounded-full text-sm bg-[--bg-card] text-[--fg-muted] hover:text-[--fg] border border-[--border] transition-all" data-filter="ads">Ads</button>
</div>
<!-- Policy Grid -->
<div id="policy-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Cards will be inserted here -->
</div>
</div>
</section>
<!-- Builder Section -->
<section id="builder-section" class="tab-content hidden min-h-screen py-12">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="grid lg:grid-cols-2 gap-8">
<!-- Controls -->
<div class="space-y-6 animate-in">
<h2 class="text-3xl font-bold">Policy Builder</h2>
<p class="text-[--fg-muted]">Toggle sandbox attributes to generate a custom policy configuration.</p>
<div class="bg-[--bg-card] rounded-xl border border-[--border] p-6">
<h3 class="text-lg font-semibold mb-4">Core Attributes</h3>
<div id="sandbox-toggles" class="space-y-3">
<!-- Toggles will be inserted here -->
</div>
</div>
<div class="bg-[--bg-card] rounded-xl border border-[--border] p-6">
<h3 class="text-lg font-semibold mb-4">Additional Options</h3>
<div class="space-y-4">
<div>
<label class="block text-sm text-[--fg-muted] mb-2">Allow-Origin Pattern</label>
<input type="text" id="allow-origin" placeholder="e.g., https://trusted.example.com"
class="w-full px-4 py-2 bg-[--code-bg] border border-[--border] rounded-lg text-sm font-mono focus:border-[--accent] transition-colors">
</div>
<div>
<label class="block text-sm text-[--fg-muted] mb-2">Credential Mode</label>
<select id="credential-mode" class="w-full px-4 py-2 bg-[--code-bg] border border-[--border] rounded-lg text-sm focus:border-[--accent] transition-colors">
<option value="omit">omit - No credentials</option>
<option value="same-origin">same-origin - Same origin only</option>
<option value="include">include - All credentials</option>
</select>
</div>
</div>
</div>
</div>
<!-- Output -->
<div class="space-y-6 animate-in" style="animation-delay: 0.15s">
<div class="flex items-center justify-between">
<h2 class="text-3xl font-bold">Generated Config</h2>
<button id="copy-config" class="flex items-center gap-2 px-4 py-2 bg-[--accent] text-[--bg] rounded-lg text-sm font-medium hover:opacity-90 transition-opacity">
<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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
</svg>
Copy
</button>
</div>
<div class="code-block p-4">
<div class="flex items-center gap-2 mb-3 pb-3 border-b border-[--border]">
<span class="w-3 h-3 rounded-full bg-[--danger]"></span>
<span class="w-3 h-3 rounded-full bg-[--warning]"></span>
<span class="w-3 h-3 rounded-full bg-[--accent]"></span>
<span class="text-xs text-[--fg-muted] ml-2">iframe-attribute.html</span>
</div>
<pre id="config-output" class="font-mono text-sm overflow-x-auto"></pre>
</div>
<div class="bg-[--bg-card] rounded-xl border border-[--border] p-6">
<h3 class="text-lg font-semibold mb-3">Security Assessment</h3>
<div id="security-assessment" class="space-y-3">
<!-- Assessment will be inserted here -->
</div>
</div>
<div class="bg-[--bg-elevated] rounded-xl border border-[--border] p-6">
<h3 class="text-lg font-semibold mb-3 flex items-center gap-2">
<svg class="w-5 h-5 text-[--warning]" 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>
Recommendations
</h3>
<ul id="recommendations" class="space-y-2 text-sm text-[--fg-muted]">
<!-- Recommendations will be inserted here -->
</ul>
</div>
</div>
</div>
</div>
</section>
<!-- Contracts Section -->
<section id="contracts-section" class="tab-content hidden min-h-screen py-12">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="max-w-4xl animate-in">
<h2 class="text-3xl font-bold mb-4">postMessage Contracts</h2>
<p class="text-[--fg-muted] mb-8">Type-safe communication patterns between parent frame and sandboxed iframe.</p>
<div id="contracts-container" class="space-y-6">
<!-- Contracts will be inserted here -->
</div>
</div>
</div>
</section>
<!-- CSP Section -->
<section id="csp-section" class="tab-content hidden min-h-screen py-12">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="max-w-4xl animate-in">
<h2 class="text-3xl font-bold mb-4">CSP Integration</h2>
<p class="text-[--fg-muted] mb-8">Content Security Policy directives for iframe sandboxing.</p>
<div class="grid gap-6">
<!-- CSP Examples will be inserted here -->
<div id="csp-examples"></div>
</div>
</div>
</div>
</section>
</main>
<!-- Toast notification -->
<div id="toast" class="fixed bottom-6 right-6 px-4 py-3 bg-[--accent] text-[--bg] rounded-lg font-medium transform translate-y-20 opacity-0 transition-all duration-300 z-50">
Copied to clipboard
</div>
<script>
// ============================================
// DATA
// ============================================
const sandboxAttributes = [
{ key: 'allow-downloads', desc: 'Allow file downloads', risk: 'low' },
{ key: 'allow-forms', desc: 'Allow form submission', risk: 'medium' },
{ key: 'allow-modals', desc: 'Allow modal dialogs', risk: 'medium' },
{ key: 'allow-orientation-lock', desc: 'Allow screen orientation lock', risk: 'low' },
{ key: 'allow-pointer-lock', desc: 'Allow pointer lock API', risk: 'medium' },
{ key: 'allow-popups', desc: 'Allow popup windows', risk: 'high' },
{ key: 'allow-popups-to-escape-sandbox', desc: 'Allow popups to open unsandboxed', risk: 'high' },
{ key: 'allow-presentation', desc: 'Allow presentation sessions', risk: 'low' },
{ key: 'allow-same-origin', desc: 'Allow treated as same origin', risk: 'high' },
{ key: 'allow-scripts', desc: 'Allow JavaScript execution', risk: 'high' },
{ key: 'allow-top-navigation', desc: 'Allow navigating top frame', risk: 'high' },
{ key: 'allow-top-navigation-by-user-activation', desc: 'Allow top nav via user gesture', risk: 'medium' },
{ key: 'allow-top-navigation-to-custom-protocols', desc: 'Allow custom protocol navigation', risk: 'high' }
];
const policies = [
{
id: 'minimal',
name: 'Minimal Trust',
category: 'ads',
security: 'high',
description: 'Maximum isolation for untrusted content. No scripts, forms, or navigation.',
attributes: [],
useCase: 'Static ad content, user-submitted HTML sanitization',
csp: "frame-src 'self'; sandbox;",
postMessage: false
},
{
id: 'display-only',
name: 'Display Only',
category: 'embed',
security: 'high',
description: 'Render content with scripts but no network access or forms.',
attributes: ['allow-scripts'],
useCase: 'Charts, read-only embeds, visualizations',
csp: "frame-src 'self'; sandbox allow-scripts;",
postMessage: true
},
{
id: 'interactive-widget',
name: 'Interactive Widget',
category: 'widget',
security: 'medium',
description: 'Scripts and forms enabled with same-origin communication.',
attributes: ['allow-scripts', 'allow-forms', 'allow-same-origin'],
useCase: 'Search widgets, calculators, form components',
csp: "frame-src 'self' https://cdn.trusted.com; sandbox allow-scripts allow-forms allow-same-origin;",
postMessage: true
},
{
id: 'cross-origin-widget',
name: 'Cross-Origin Widget',
category: 'widget',
security: 'medium',
description: 'Scripts enabled for cross-origin embeds via postMessage.',
attributes: ['allow-scripts'],
useCase: 'Third-party widgets, social embeds',
csp: "frame-src 'self' https://embed.example.com; sandbox allow-scripts;",
postMessage: true
},
{
id: 'embedded-app',
name: 'Embedded Application',
category: 'app',
security: 'medium',
description: 'Full application capabilities with controlled navigation.',
attributes: ['allow-scripts', 'allow-forms', 'allow-same-origin', 'allow-modals', 'allow-downloads'],
useCase: 'Micro-frontends, embedded dashboards',
csp: "frame-src 'self'; sandbox allow-scripts allow-forms allow-same-origin allow-modals allow-downloads;",
postMessage: true
},
{
id: 'full-app',
name: 'Full Application',
category: 'app',
security: 'low',
description: 'Maximum flexibility for trusted applications.',
attributes: ['allow-scripts', 'allow-forms', 'allow-same-origin', 'allow-modals', 'allow-popups', 'allow-downloads'],
useCase: 'Trusted partner integrations, admin panels',
csp: "frame-src 'self' https://trusted.partner.com; sandbox allow-scripts allow-forms allow-same-origin allow-modals allow-popups allow-downloads;",
postMessage: true
},
{
id: 'oauth-frame',
name: 'OAuth Flow',
category: 'widget',
security: 'medium',
description: 'OAuth authentication with controlled top navigation.',
attributes: ['allow-scripts', 'allow-forms', 'allow-same-origin', 'allow-top-navigation-by-user-activation'],
useCase: 'OAuth authentication flows, SSO',
csp: "frame-src 'self' https://auth.example.com; sandbox allow-scripts allow-forms allow-same-origin allow-top-navigation-by-user-activation;",
postMessage: true
},
{
id: 'media-embed',
name: 'Media Embed',
category: 'embed',
security: 'high',
description: 'Media playback with pointer lock for games/players.',
attributes: ['allow-scripts', 'allow-same-origin', 'allow-pointer-lock'],
useCase: 'Video players, game embeds, interactive media',
csp: "frame-src 'self' https://media.example.com; sandbox allow-scripts allow-same-origin allow-pointer-lock;",
postMessage: true
},
{
id: 'document-viewer',
name: 'Document Viewer',
category: 'embed',
security: 'high',
description: 'PDF/document viewing with download capability.',
attributes: ['allow-scripts', 'allow-downloads'],
useCase: 'PDF viewers, document previews',
csp: "frame-src 'self' https://docs.example.com; sandbox allow-scripts allow-downloads;",
postMessage: false
}
];
const postMessageContracts = [
{
name: 'Resize Contract',
pattern: 'resize',
description: 'Allow iframe to request parent container resize',
code: {
parent: `window.addEventListener('message', (event) => {
if (event.origin !== 'https://embed.example.com') return;
if (event.data.type === 'resize') {
const { width, height } = event.data.payload;
iframe.style.width = width + 'px';
iframe.style.height = height + 'px';
}
});`,
child: `parent.postMessage({
type: 'resize',
payload: { width: 800, height: 600 }
}, 'https://parent.example.com');`
}
},
{
name: 'Action Contract',
pattern: 'action',
description: 'Typed action protocol with validation',
code: {
parent: `const ALLOWED_ACTIONS = ['navigate', 'submit', 'close'];
const ALLOWED_ORIGINS = ['https://trusted.example.com'];
window.addEventListener('message', (event) => {
if (!ALLOWED_ORIGINS.includes(event.origin)) return;
const { action, payload, nonce } = event.data;
if (!ALLOWED_ACTIONS.includes(action)) return;
if (!verifyNonce(nonce)) return;
dispatch(action, payload);
});`,
child: `const sendAction = (action, payload) => {
parent.postMessage({
action,
payload,
nonce: crypto.randomUUID()
}, 'https://parent.example.com');
};`
}
},
{
name: 'RPC Contract',
pattern: 'rpc',
description: 'Request-response pattern with correlation IDs',
code: {
parent: `const pending = new Map();
window.addEventListener('message', (event) => {
if (event.origin !== 'https://embed.example.com') return;
const { id, method, result, error } = event.data;
if (pending.has(id)) {
const { resolve, reject } = pending.get(id);
pending.delete(id);
error ? reject(error) : resolve(result);
}
});
const call = (method, params) => {
const id = crypto.randomUUID();
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
iframe.contentWindow.postMessage({ id, method, params }, '*');
setTimeout(() => {
pending.delete(id);
reject(new Error('Timeout'));
}, 5000);
});
};`,
child: `window.addEventListener('message', async (event) => {
const { id, method, params } = event.data;
try {
const result = await handlers[method]?.(params);
parent.postMessage({ id, result }, event.origin);
} catch (error) {
parent.postMessage({ id, error: error.message }, event.origin);
}
});`
}
}
];
const cspExamples = [
{
title: 'Basic Sandbox Frame Directive',
code: `Content-Security-Policy:
frame-src 'self' https://trusted.cdn.com;
frame-ancestors 'self';
sandbox allow-scripts allow-forms;`
},
{
title: 'Strict Isolation Policy',
code: `Content-Security-Policy:
default-src 'none';
frame-src 'self';
sandbox;
report-uri /csp-reports;`
},
{
title: 'Per-Domain Policy with Report-Only',
code: `Content-Security-Policy-Report-Only:
frame-src 'self' https://*.example.com;
frame-ancestors 'self' https://app.example.com;
sandbox allow-scripts allow-same-origin;
report-uri /csp-debug;`
},
{
title: 'Full Application with Permissions Policy',
code: `Content-Security-Policy:
frame-src 'self';
sandbox allow-scripts allow-forms allow-same-origin allow-modals;
Permissions-Policy:
accelerometer=(self),
camera=(self "https://embed.example.com"),
microphone=()`
}
];
// ============================================
// STATE
// ============================================
let activeToggles = new Set();
let activeFilter = 'all';
// ============================================
// DOM INIT
// ============================================
const policyGrid = document.getElementById('policy-grid');
const sandboxToggles = document.getElementById('sandbox-toggles');
const configOutput = document.getElementById('config-output');
const securityAssessment = document.getElementById('security-assessment');
const recommendations = document.getElementById('recommendations');
const contractsContainer = document.getElementById('contracts-container');
const cspExamplesContainer = document.getElementById('csp-examples');
const toast = document.getElementById('toast');
// ============================================
// RENDER FUNCTIONS
// ============================================
function renderPolicyCards() {
const filtered = activeFilter === 'all'
? policies
: policies.filter(p => p.category === activeFilter);
policyGrid.innerHTML = filtered.map((policy, idx) => `
<article class="policy-card bg-[--bg-card] border border-[--border] rounded-xl p-6 cursor-pointer animate-in"
style="animation-delay: ${0.1 + idx * 0.05}s"
data-policy-id="${policy.id}"
tabindex="0"
role="button"
aria-label="Copy ${policy.name} policy configuration">
<div class="flex items-start justify-between mb-4">
<div class="flex items-center gap-2">
<span class="px-2 py-0.5 text-xs font-medium rounded bg-[--accent-dim] text-[--accent]">${policy.category}</span>
${policy.postMessage ? '<span class="px-2 py-0.5 text-xs font-medium rounded bg-[--bg-elevated] text-[--fg-muted]">postMessage</span>' : ''}
</div>
<span class="security-${policy.security} text-xs font-medium uppercase">${policy.security} security</span>
</div>
<h3 class="text-xl font-bold mb-2">${policy.name}</h3>
<p class="text-[--fg-muted] text-sm mb-4">${policy.description}</p>
<div class="bg-[--code-bg] rounded-lg p-3 mb-4">
<code class="font-mono text-xs text-[--accent]">sandbox="${policy.attributes.length ? policy.attributes.join(' ') : ''}"</code>
</div>
<div class="text-xs text-[--fg-muted]">
<span class="font-medium">Use case:</span> ${policy.useCase}
</div>
</article>
`).join('');
// Attach click handlers
document.querySelectorAll('.policy-card').forEach(card => {
card.addEventListener('click', () => copyPolicy(card.dataset.policyId));
card.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
copyPolicy(card.dataset.policyId);
}
});
});
}
function renderToggles() {
sandboxToggles.innerHTML = sandboxAttributes.map(attr => `
<div class="flex items-center justify-between py-2">
<div>
<label class="text-sm font-medium cursor-pointer" for="toggle-${attr.key}">${attr.key}</label>
<p class="text-xs text-[--fg-muted]">${attr.desc}</p>
</div>
<div class="flex items-center gap-3">
<span class="text-xs px-2 py-0.5 rounded ${
attr.risk === 'high' ? 'bg-red-500/20 text-red-400' :
attr.risk === 'medium' ? 'bg-yellow-500/20 text-yellow-400' :
'bg-green-500/20 text-green-400'
}">${attr.risk} risk</span>
<button
id="toggle-${attr.key}"
class="toggle-switch"
data-attr="${attr.key}"
role="switch"
aria-checked="false"
aria-label="Toggle ${attr.key}">
</button>
</div>
</div>
`).join('');
// Attach toggle handlers
document.querySelectorAll('.toggle-switch').forEach(toggle => {
toggle.addEventListener('click', () => {
const attr = toggle.dataset.attr;
if (activeToggles.has(attr)) {
activeToggles.delete(attr);
toggle.classList.remove('active');
toggle.setAttribute('aria-checked', 'false');
} else {
activeToggles.add(attr);
toggle.classList.add('active');
toggle.setAttribute('aria-checked', 'true');
}
updateBuilderOutput();
});
});
}
function updateBuilderOutput() {
const allowOrigin = document.getElementById('allow-origin').value;
const credentialMode = document.getElementById('credential-mode').value;
const attrs = Array.from(activeToggles);
const sandboxValue = attrs.length ? attrs.join(' ') : '';
let output = `<span class="text-[--fg-muted]"><iframe</span>\n`;
output += ` <span class="text-[--accent]">sandbox</span>=<span class="text-[--warning]">"${sandboxValue}"</span>\n`;
if (allowOrigin) {
output += ` <span class="text-[--accent]">allow</span>=<span class="text-[--warning]">"origin ${allowOrigin}"</span>\n`;
}
output += ` <span class="text-[--accent]">credentialless</span>=<span class="text-[--warning]">"${credentialMode !== 'include'}"</span>\n`;
output += `<span class="text-[--fg-muted]">></iframe></span>`;
configOutput.innerHTML = output;
updateSecurityAssessment();
updateRecommendations();
}
function updateSecurityAssessment() {
const attrs = Array.from(activeToggles);
const highRisk = ['allow-popups', 'allow-popups-to-escape-sandbox', 'allow-same-origin', 'allow-scripts', 'allow-top-navigation', 'allow-top-navigation-to-custom-protocols'];
const mediumRisk = ['allow-forms', 'allow-modals', 'allow-pointer-lock', 'allow-top-navigation-by-user-activation'];
const enabledHigh = attrs.filter(a => highRisk.includes(a));
const enabledMedium = attrs.filter(a => mediumRisk.includes(a));
let securityLevel = 'high';
if (enabledHigh.length > 2 || enabledHigh.includes('allow-same-origin')) securityLevel = 'low';
else if (enabledHigh.length > 0 || enabledMedium.length > 2) securityLevel = 'medium';
const checks = [
{ label: 'Cross-origin isolation', pass: !attrs.includes('allow-same-origin') },
{ label: 'Navigation control', pass: !attrs.includes('allow-top-navigation') },
{ label: 'Popup containment', pass: !attrs.includes('allow-popups-to-escape-sandbox') },
{ label: 'Script sandboxing', pass: !attrs.includes('allow-scripts') || attrs.includes('allow-same-origin') }
];
securityAssessment.innerHTML = `
<div class="flex items-center justify-between mb-3">
<span class="text-sm text-[--fg-muted]">Overall Security</span>
<span class="security-${securityLevel} font-bold uppercase">${securityLevel}</span>
</div>
${checks.map(c => `
<div class="flex items-center gap-2 text-sm">
${c.pass
? '<svg class="w-4 h-4 text-[--accent]" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>'
: '<svg class="w-4 h-4 text-[--warning]" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>'
}
<span class="${c.pass ? 'text-[--fg-muted]' : 'text-[--warning]'}">${c.label}</span>
</div>
`).join('')}
`;
}
function updateRecommendations() {
const attrs = Array.from(activeToggles);
const recs = [];
if (attrs.includes('allow-scripts') && !attrs.includes('allow-same-origin')) {
recs.push('Consider using postMessage for communication instead of enabling same-origin');
}
if (attrs.includes('allow-popups')) {
recs.push('Add noopener/noreferrer to popup links to prevent tabnabbing');
}
if (attrs.includes('allow-forms') && !attrs.includes('allow-same-origin')) {
recs.push('Form submissions will be blocked without same-origin; validate server-side');
}
if (attrs.includes('allow-top-navigation')) {
recs.push('Consider allow-top-navigation-by-user-activation instead for user-triggered nav');
}
if (attrs.length === 0) {
recs.push('Empty sandbox provides maximum isolation but severely limits functionality');
}
if (!attrs.includes('allow-scripts') && attrs.includes('allow-forms')) {
recs.push('Forms without scripts may have limited client-side validation');
}
recommendations.innerHTML = recs.length
? recs.map(r => `<li class="flex items-start gap-2"><span class="text-[--warning]">•</span> ${r}</li>`).join('')
: '<li class="text-[--accent]">No additional recommendations for this configuration</li>';
}
function renderContracts() {
contractsContainer.innerHTML = postMessageContracts.map((contract, idx) => `
<div class="bg-[--bg-card] border border-[--border] rounded-xl overflow-hidden animate-in" style="animation-delay: ${idx * 0.1}s">
<div class="p-6 border-b border-[--border]">
<div class="flex items-center justify-between">
<h3 class="text-lg font-bold">${contract.name}</h3>
<span class="px-2 py-0.5 text-xs font-mono bg-[--accent-dim] text-[--accent] rounded">${contract.pattern}</span>
</div>
<p class="text-[--fg-muted] text-sm mt-1">${contract.description}</p>
</div>
<div class="grid md:grid-cols-2 divide-y md:divide-y-0 md:divide-x divide-[--border]">
<div class="p-4">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-medium text-[--fg-muted]">PARENT FRAME</span>
<button class="copy-btn text-xs text-[--accent] hover:underline" data-code="${encodeURIComponent(contract.code.parent)}">Copy</button>
</div>
<pre class="font-mono text-xs bg-[--code-bg] p-3 rounded-lg overflow-x-auto text-[--fg-muted]">${escapeHtml(contract.code.parent)}</pre>
</div>
<div class="p-4">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-medium text-[--fg-muted]">IFRAME</span>
<button class="copy-btn text-xs text-[--accent] hover:underline" data-code="${encodeURIComponent(contract.code.child)}">Copy</button>
</div>
<pre class="font-mono text-xs bg-[--code-bg] p-3 rounded-lg overflow-x-auto text-[--fg-muted]">${escapeHtml(contract.code.child)}</pre>
</div>
</div>
</div>
`).join('');
}
function renderCSPExamples() {
cspExamplesContainer.innerHTML = cspExamples.map((example, idx) => `
<div class="bg-[--bg-card] border border-[--border] rounded-xl overflow-hidden animate-in" style="animation-delay: ${idx * 0.1}s">
<div class="p-4 border-b border-[--border]">
<h3 class="font-bold">${example.title}</h3>
</div>
<div class="p-4">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-medium text-[--fg-muted]">HTTP HEADER</span>
<button class="copy-btn text-xs text-[--accent] hover:underline" data-code="${encodeURIComponent(example.code)}">Copy</button>
</div>
<pre class="font-mono text-xs bg-[--code-bg] p-3 rounded-lg overflow-x-auto text-[--accent]">${escapeHtml(example.code)}</pre>
</div>
</div>
`).join('');
}
// ============================================
// UTILITIES
// ============================================
function escapeHtml(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function showToast(message) {
toast.textContent = message;
toast.classList.remove('translate-y-20', 'opacity-0');
setTimeout(() => {
toast.classList.add('translate-y-20', 'opacity-0');
}, 2000);
}
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
showToast('Copied to clipboard');
} catch (err) {
showToast('Failed to copy');
}
}
function copyPolicy(policyId) {
const policy = policies.find(p => p.id === policyId);
if (!policy) return;
const attrs = policy.attributes.length ? ` sandbox="${policy.attributes.join(' ')}"` : '';
const html = `<iframe${attrs}></iframe>`;
copyToClipboard(html);
}
// ============================================
// EVENT HANDLERS
// ============================================
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tab = btn.dataset.tab;
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(b => {
b.classList.remove('tab-active', 'text-[--fg]');
b.classList.add('text-[--fg-muted]');
});
btn.classList.add('tab-active', 'text-[--fg]');
btn.classList.remove('text-[--fg-muted]');
// Update sections
document.querySelectorAll('.tab-content').forEach(section => {
section.classList.add('hidden');
});
document.getElementById(`${tab}-section`).classList.remove('hidden');
});
});
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.addEventListener('click', () => {
activeFilter = btn.dataset.filter;
document.querySelectorAll('.filter-btn').forEach(b => {
b.classList.remove('active', 'bg-[--accent]', 'text-[--bg]');
b.classList.add('bg-[--bg-card]', 'text-[--fg-muted]', 'border', 'border-[--border]');
});
btn.classList.add('active', 'bg-[--accent]', 'text-[--bg]');
btn.classList.remove('bg-[--bg-card]', 'text-[--fg-muted]', 'border', 'border-[--border]');
renderPolicyCards();
});
});
document.getElementById('copy-config').addEventListener('click', () => {
const text = configOutput.textContent;
copyToClipboard(text);
});
document.getElementById('allow-origin').addEventListener('input', updateBuilderOutput);
document.getElementById('credential-mode').addEventListener('change', updateBuilderOutput);
document.addEventListener('click', (e) => {
if (e.target.classList.contains('copy-btn')) {
const code = decodeURIComponent(e.target.dataset.code);
copyToClipboard(code);
}
});
// Scroll reveal with IntersectionObserver
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.animationPlayState = 'running';
observer.unobserve(entry.target);
}
});
}, observerOptions);
// ============================================
// INIT
// ============================================
function init() {
renderPolicyCards();
renderToggles();
updateBuilderOutput();
renderContracts();
renderCSPExamples();
// Observe animate-in elements
document.querySelectorAll('.animate-in').forEach(el => {
el.style.animationPlayState = 'paused';
observer.observe(el);
});
// Re-observe after initial render
setTimeout(() => {
document.querySelectorAll('.animate-in').forEach(el => {
el.style.animationPlayState = 'running';
});
}, 100);
}
init();
</script>
</body>
</html>