// pages/security.jsx

const TOKEN_EXAMPLE = `{
  "sub": "service/code-executor",
  "iat": 1748649600,
  "exp": 1748736000,
  "caps": {
    "filesystem": ["/tmp", "/data/uploads"],
    "network": false,
    "syscalls": ["read", "write", "exit"],
    "max_memory_mb": 256,
    "max_timeout_ms": 30000
  }
}
// Signed with HMAC-SHA256(VELA_TOKEN_SECRET, payload)`;

const POLICY_EXAMPLE = `deny_patterns:
  - "rm -rf"
  - "curl\\\\s+https?://"
  - "wget"
  - "chmod.*777"
  - "nc\\\\s+-"        # netcat

require_approval_for:
  - pattern: "sudo"
    reason: "privilege escalation requires review"
  - pattern: "pip install"
    reason: "package installation must be pre-approved"

max_timeout_ms: 15000`;

const ALERT_EXAMPLE = `{
  "execution_id": "a1b2c3d4",
  "alerts": [
    {
      "severity": "HIGH",
      "rule_id": "sensitive_file_access",
      "description": "Process attempted to access /etc/shadow"
    },
    {
      "severity": "CRITICAL",
      "rule_id": "syscall_rate_spike",
      "description": "Syscall rate exceeded 847/s (limit: 500/s)"
    }
  ]
}`;

const DETECTION_RULES = [
  { rule: 'sensitive_file_access', severity: 'HIGH', trigger: '/etc/shadow, /root/.ssh/*, /proc/*' },
  { rule: 'syscall_rate_spike', severity: 'CRITICAL', trigger: 'Syscall rate > 500/s' },
  { rule: 'private_network_access', severity: 'HIGH', trigger: 'Connections to RFC-1918 addresses' },
  { rule: 'command_pattern_match', severity: 'MEDIUM', trigger: 'Custom regexes in intrusion_rules.toml' },
];

const NOT_PROTECTED = [
  { title: 'Kernel exploits in the guest', desc: 'Use a hardened, minimal guest kernel image. Vela doesn\'t patch CVEs in the kernel running inside the VM.' },
  { title: 'Physical host access', desc: 'An attacker with physical access to your hardware bypasses all software isolation. Secure your infrastructure.' },
  { title: 'Compromised TOKEN_SECRET', desc: 'Rotate VELA_TOKEN_SECRET frequently. Store it in a secrets manager, never in source code or env files.' },
  { title: 'Unbounded concurrency', desc: 'Use --pool-size and max_requests_per_minute to prevent resource exhaustion from too many concurrent VMs.' },
];

function SecuritySectionBlock({ title, children, style = {} }) {
  return (
    <AnimEl style={{ marginBottom: '4rem', ...style }}>
      <h2 style={{ fontSize: '1.375rem', fontWeight: 700, marginBottom: '1.25rem', paddingBottom: '0.75rem', borderBottom: '1px solid var(--color-border)' }}>{title}</h2>
      {children}
    </AnimEl>
  );
}

function SecurityPage() {
  useSEO("Security — Vela Runtime", "In-depth security architecture and policies.");
  return (
    <div style={{ paddingTop: '64px', minHeight: '100vh', background: 'var(--color-bg)' }}>
      {/* Hero */}
      <div style={{ padding: '5rem 0 4rem', textAlign: 'center' }} className="bg-hero-glow bg-grid">
        <div className="container">
          <AnimEl>
            <span className="badge badge-brand" style={{ marginBottom: '1.25rem' }}>
              <IcoShield size={13} style={{ marginRight: '0.35rem' }} />Security
            </span>
            <h1 style={{ fontSize: 'clamp(2rem, 5vw, 3rem)', fontWeight: 800, letterSpacing: '-0.03em', marginBottom: '1rem' }}>
              Security model, documented
            </h1>
            <p style={{ color: 'var(--color-muted)', fontSize: '1.125rem', maxWidth: '520px', margin: '0 auto' }}>
              We don't hide how the security works. Here's everything.
            </p>
          </AnimEl>
        </div>
      </div>

      <div className="container" style={{ maxWidth: '860px', padding: '4rem 1.5rem 6rem' }}>

        {/* Isolation model */}
        <SecuritySectionBlock title="Isolation model">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '1.5rem' }}>
            <div style={{ color: 'var(--color-muted)', fontSize: '0.9375rem', lineHeight: 1.8 }}>
              <p style={{ marginBottom: '1rem' }}>Vela runs every execution in a fresh Firecracker micro-VM — the same technology that powers AWS Lambda and Fargate.</p>
              <p style={{ marginBottom: '1rem' }}>Unlike Docker containers, Firecracker VMs provide hardware-level isolation through KVM. Your host kernel is <strong style={{ color: 'var(--color-text)' }}>never shared</strong> with untrusted code. When the execution finishes, the VM is destroyed.</p>
              <p>Pre-warmed VM pools amortize cold-start overhead. With <code style={{ fontFamily: 'var(--font-mono)', background: 'var(--color-surface)', padding: '0.1em 0.35em', borderRadius: '3px', fontSize: '0.85em', color: 'var(--color-brand-400)' }}>--pool-size 4</code>, p50 latency drops to ~150ms.</p>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
              {[
                { label: 'p50 latency (warmed)', value: '~150ms', color: 'var(--color-green)' },
                { label: 'Cold start', value: '~900ms', color: 'var(--color-amber)' },
                { label: 'Leaks between executions', value: '0', color: 'var(--color-green)' },
                { label: 'Shared host kernel', value: 'Never', color: 'var(--color-green)' },
              ].map(({ label, value, color }) => (
                <div key={label} style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', padding: '0.875rem 1rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ color: 'var(--color-muted)', fontSize: '0.875rem' }}>{label}</span>
                  <span style={{ color, fontFamily: 'var(--font-mono)', fontSize: '0.875rem', fontWeight: 700 }}>{value}</span>
                </div>
              ))}
            </div>
          </div>
        </SecuritySectionBlock>

        {/* Token model */}
        <SecuritySectionBlock title="HMAC-SHA256 capability tokens">
          <p style={{ color: 'var(--color-muted)', marginBottom: '1.5rem', lineHeight: 1.75 }}>
            Capability tokens are HMAC-SHA256 signed JSON payloads. The daemon verifies the signature cryptographically before executing anything — no valid token, no execution. Tokens scope exactly what a caller can do.
          </p>
          <CodeBlock code={TOKEN_EXAMPLE} lang="json" filename="token payload (decoded)" />
          <div style={{ marginTop: '1.25rem', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '0.75rem' }}>
            {['Filesystem allowlist', 'Network on/off', 'Syscall allowlist', 'Memory cap (MB)', 'Timeout cap (ms)', 'Expiry (Unix timestamp)'].map(f => (
              <div key={f} style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', fontSize: '0.875rem', color: 'var(--color-muted)' }}>
                <IcoCheck size={13} style={{ color: 'var(--color-brand-400)', flexShrink: 0 }} />{f}
              </div>
            ))}
          </div>
        </SecuritySectionBlock>

        {/* Policy engine */}
        <SecuritySectionBlock title="Policy enforcement">
          <p style={{ color: 'var(--color-muted)', marginBottom: '1.5rem', lineHeight: 1.75 }}>
            Define what's allowed at the organization level. Vela compiles YAML rules at startup into pre-compiled regexes for zero-overhead enforcement. Three decision types: <strong style={{ color: 'var(--color-text)' }}>Allow</strong>, <strong style={{ color: 'var(--color-text)' }}>Deny</strong>, <strong style={{ color: 'var(--color-text)' }}>RequireApproval</strong>. Vela <strong style={{ color: 'var(--color-text)' }}>fails closed</strong> by default if an external policy endpoint is unreachable.
          </p>
          <CodeBlock code={POLICY_EXAMPLE} lang="yaml" filename="policy.yaml" />
        </SecuritySectionBlock>

        {/* Intrusion detection */}
        <SecuritySectionBlock title="Intrusion detection">
          <p style={{ color: 'var(--color-muted)', marginBottom: '1.5rem', lineHeight: 1.75 }}>
            Vela watches every execution for anomalous behavior and attaches structured alerts to the telemetry record. Rules are enabled by default — no configuration required.
          </p>
          <div style={{ border: '1px solid var(--color-border)', borderRadius: 'var(--radius-lg)', overflow: 'hidden', marginBottom: '1.5rem' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.875rem' }}>
              <thead>
                <tr style={{ background: 'var(--color-surface-2)', borderBottom: '1px solid var(--color-border)' }}>
                  {['Rule', 'Severity', 'Trigger'].map(h => (
                    <th key={h} style={{ padding: '0.75rem 1rem', textAlign: 'left', fontWeight: 600, color: 'var(--color-text)' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {DETECTION_RULES.map((r, i) => (
                  <tr key={r.rule} style={{ borderBottom: i < DETECTION_RULES.length - 1 ? '1px solid var(--color-border)' : 'none' }}>
                    <td style={{ padding: '0.75rem 1rem', fontFamily: 'var(--font-mono)', color: 'var(--color-brand-400)', fontSize: '0.8rem' }}>{r.rule}</td>
                    <td style={{ padding: '0.75rem 1rem' }}>
                      <span className={`badge ${r.severity === 'CRITICAL' ? 'badge-red' : r.severity === 'HIGH' ? 'badge-amber' : 'badge-muted'}`}>{r.severity}</span>
                    </td>
                    <td style={{ padding: '0.75rem 1rem', color: 'var(--color-muted)' }}>{r.trigger}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <CodeBlock code={ALERT_EXAMPLE} lang="json" filename="alert output" />
        </SecuritySectionBlock>

        {/* What Vela does NOT protect */}
        <AnimEl style={{ marginBottom: '4rem' }}>
          <div style={{ background: 'rgba(239,68,68,0.04)', border: '1px solid rgba(239,68,68,0.15)', borderRadius: 'var(--radius-lg)', padding: '2rem' }}>
            <h2 style={{ fontSize: '1.25rem', fontWeight: 700, marginBottom: '1.5rem', color: '#f87171', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
              <IcoAlertTriangle size={18} /> What Vela does NOT protect against
            </h2>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '1.25rem' }}>
              {NOT_PROTECTED.map(({ title, desc }) => (
                <div key={title}>
                  <div style={{ fontWeight: 600, fontSize: '0.9375rem', marginBottom: '0.375rem', color: 'var(--color-text)' }}>{title}</div>
                  <p style={{ color: 'var(--color-muted)', fontSize: '0.875rem', lineHeight: 1.65, margin: 0 }}>{desc}</p>
                </div>
              ))}
            </div>
          </div>
        </AnimEl>

        {/* Vulnerability reporting */}
        <SecuritySectionBlock title="Reporting vulnerabilities">
          <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-lg)', padding: '1.75rem' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
              <div style={{ display: 'flex', gap: '0.625rem', alignItems: 'center' }}>
                <span style={{ color: 'var(--color-muted)', fontSize: '0.875rem' }}>Email:</span>
                <a href="mailto:security@getvela.io" style={{ color: 'var(--color-brand-400)', fontFamily: 'var(--font-mono)', fontSize: '0.875rem' }}>security@getvela.io</a>
              </div>
              <div style={{ display: 'flex', gap: '0.625rem', alignItems: 'center' }}>
                <span style={{ color: 'var(--color-muted)', fontSize: '0.875rem' }}>Response time:</span>
                <span style={{ color: 'var(--color-text)', fontSize: '0.875rem' }}>We aim to respond within 48 hours</span>
              </div>
              <div style={{ display: 'flex', gap: '0.625rem', alignItems: 'center' }}>
                <span style={{ color: 'var(--color-muted)', fontSize: '0.875rem' }}>Disclosure:</span>
                <span style={{ color: 'var(--color-text)', fontSize: '0.875rem' }}>Coordinated responsible disclosure, 90-day window</span>
              </div>
            </div>
            <p style={{ color: 'var(--color-muted)', fontSize: '0.875rem', lineHeight: 1.7, marginTop: '1.25rem', paddingTop: '1.25rem', borderTop: '1px solid var(--color-border)' }}>
              Please include a description of the vulnerability, steps to reproduce, and your assessment of the impact. We do not currently run a bug bounty program, but we acknowledge all valid reports publicly (with your permission).
            </p>
          </div>
        </SecuritySectionBlock>
      </div>
    </div>
  );
}

Object.assign(window, { SecurityPage });
