Skip to content

Security: peresramirez/wonderdive

Security

SECURITY.md

Security

Wonderdive is used by learners from 12 up, often on shared links, so the bar is: no leaked keys, no learner data kept longer than needed, and nothing a learner types, uploads, draws or says can change what the app executes.

1. Keys never leave the server

  • All keys live only in .env (git-ignored, chmod 600) locally and in FastAPI Cloud / Vercel secret stores in production. .env.example lists variable names with empty placeholders only.
  • Every third-party vendor call (F13 Espresso, Gemini, Gradium, Tavily, and the Supabase service_role key) runs strictly server-side inside apps/api.
  • The browser bundle (apps/web) may read only three public values:
    1. NEXT_PUBLIC_API_BASE_URL
    2. NEXT_PUBLIC_SUPABASE_URL
    3. NEXT_PUBLIC_SUPABASE_ANON_KEY (safe only because Row-Level Security is enabled on all 13 public.* tables in supabase/migrations/20261128000200_rls_and_views.sql and 20261128180000_unlisted_by_slug.sql)
  • Feature flags are fetched at runtime from GET /v1/health (never via NEXT_PUBLIC_FLAG_* env vars).
  • Browser microphone sessions never touch GRADIUM_API_KEY; POST /v1/voice/token issues a short-lived, single-use, region-pinned Gradium STT token alongside its matching ws_url (wss://eu.api.gradium.ai/api/speech/asr by default, with Cache-Control: no-store), and apps/web/lib/gradium-mic.ts explicitly rejects raw gsk_* keys.
  • apps/api/app/core/config.py installs SecretRedactingFilter across every Python logger and apps/api/app/core/logging.py scrubs configured secrets, JWTs, API key prefixes, emails, and audio URIs to [REDACTED] before any structured log line or error message is emitted.
  • Commits and pull requests are scanned automatically:
    • .githooks/pre-commit: scripts/scan-secrets.mjs --staged (blocks .env/key files, known key formats, service_role JWTs, and exact values from your local .env) + gitleaks git --pre-commit --staged.
    • .githooks/pre-push: runs the secret guard and gitleaks over all files and the entire git history.
    • GitHub Actions CI (.github/workflows/security.yml, every action pinned to a 40-char commit SHA, minimal contents: read permissions by default):
      1. Secrets & history: scripts/scan-secrets.mjs --all + SHA-256 checksum-verified gitleaks (v8.30.1) over the full git history.
      2. Hygiene: verifies zero git-ignored files are tracked, apps/web source references no server secret names and only the 3 allowed NEXT_PUBLIC_* vars, and every write route in apps/api/app/routers enforces Depends(current_user) + rate_limit(...).
      3. Next.js bundle & CSP header verification: runs next build with server-only canary secrets injected into the build environment, scans .next/static and .next/server/app to verify zero server canaries, vendor keys, service_role JWTs, or extra NEXT_PUBLIC_* variables enter the bundle, and boots next start to verify live HTTP security headers and CSP on / and /sandbox.html.
      4. Dependency audit: npm audit --omit=dev --audit-level=high (. and apps/web) + pip-audit (apps/api), backed by weekly .github/dependabot.yml updates.
      5. SAST (CodeQL + Bandit): CodeQL (javascript-typescript and python, security-and-quality query suite) parses SARIF output and fails the workflow on any high/critical security finding (security-severity >= 7.0 or error-level security alert), uploading SARIF to GitHub Code Scanning automatically when repository visibility is public. bandit (-lll -ii) additionally runs high-severity Python SAST across apps/api/app.
  • If a key ever reaches a commit: rotate it immediately first, then scrub history (F13: issue a new key; Gemini: https://aistudio.google.com/apikey; Supabase: Project Settings → API keys; Gradium & Tavily: dashboard key rotation).

2. Browser security headers, CSP & animation sandbox

apps/web/middleware.ts (backed by static fallback headers in apps/web/next.config.mjs) enforces strict response headers and a per-request cryptographic nonce CSP across all routes, plus SHA-256 hash pinning on the standalone /pitch presentation deck:

Header Application routes (/, /dashboard, /lesson/[id], /play/[slug], 404 fallbacks) Animation sandbox (/sandbox.html) Pitch deck (/pitch, /pitch-deck.html)
Content-Security-Policy default-src 'self'; script-src 'self' 'nonce-<base64>' ('unsafe-eval' in dev only — never 'unsafe-inline'); style-src 'self' 'nonce-<base64>' 'sha256-<next-404-style>'; style-src-attr 'unsafe-inline'; img-src 'self' blob: data: <api> <supabase>; font-src 'self' data:; media-src 'self' blob: <api> <supabase>; connect-src 'self' <api> <supabase> <wss-supabase> wss://api.gradium.ai wss://*.gradium.ai; worker-src 'self' blob:; frame-src <origin>/sandbox.html; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self'; manifest-src 'self' (+ upgrade-insecure-requests on HTTPS) sandbox allow-scripts; frame-ancestors 'self'; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; media-src 'none'; font-src 'none'; connect-src 'none'; worker-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'; object-src 'none' default-src 'none'; script-src 'sha256-<pitch-script-1>' …; style-src 'sha256-<pitch-style-1>' …; style-src-attr 'unsafe-inline'; img-src 'self' data:; media-src blob:; font-src 'none'; connect-src 'none'; worker-src 'none'; frame-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'; object-src 'none' (+ upgrade-insecure-requests on HTTPS)
X-Frame-Options DENY SAMEORIGIN DENY
X-Content-Type-Options nosniff nosniff nosniff
Strict-Transport-Security max-age=63072000; includeSubDomains; preload max-age=63072000; includeSubDomains; preload max-age=63072000; includeSubDomains; preload
Referrer-Policy strict-origin-when-cross-origin no-referrer strict-origin-when-cross-origin
Permissions-Policy microphone=(self); camera, geolocation, payment, USB, HID, display-capture all () All powerful features () (including microphone=()) fullscreen=(self); all other powerful features ()
Cross-Origin-Opener-Policy same-origin — (framed document) same-origin
Cross-Origin-Resource-Policy same-origin same-origin same-origin
X-DNS-Prefetch-Control / X-Permitted-Cross-Domain-Policies off / none off / none off / none
  • Per-request nonce plumbing & static document coverage:
    • apps/web/middleware.ts mints a fresh 128-bit Web Crypto CSPRNG base64 nonce (generateCspNonce()) on every app request, forwards both x-nonce and Content-Security-Policy on the request headers, and sets the matching Content-Security-Policy response header. apps/web/app/layout.tsx reads x-nonce via await headers(), opting every App Router route (/, /dashboard, /lesson/[id], /play/[slug], and 404 fallbacks such as /create) into dynamic per-request rendering so Next.js stamps the nonce onto its framework and RSC bootstrap <script> tags (without echoing the nonce into any data-* attribute). 'strict-dynamic' is intentionally omitted so 'self' remains enforced for Next.js chunks and audioWorklet.addModule('/worklets/pcm-processor.js').
    • Static documents:
      1. /pitch (/pitch-deck.html in public/) stays a static standalone HTML presentation and avoids 'unsafe-inline' on both script-src and style-src via SHA-256 hashes of every inline <script> and <style> block computed automatically from public/pitch-deck.html at build time in apps/web/next.config.mjs (so edits to the deck never drift from its CSP).
      2. /sandbox.html stays a static document loaded exclusively inside <iframe sandbox="allow-scripts"> (no allow-same-origin, so window.origin === "null") with default-src 'none'; connect-src 'none'; frame-ancestors 'self'. It retains script-src 'unsafe-inline'; style-src 'unsafe-inline' only inside that opaque, networkless origin because its runtime executes AST-screened, server-verified animation code by appending a parameter-shadowed <script> node.
  • Inline CSS tightening & residual Low risk (style-src-attr 'unsafe-inline'):
    • style-src disallows 'unsafe-inline' in production (style-src 'self' 'nonce-<base64>' plus the build-time SHA-256 hash of Next.js's built-in 404 HTTPAccessErrorFallback <style> tag extracted from next in apps/web/next.config.mjs), blocking injected <style> elements and rogue @import / @font-face / CSS attribute-selector exfiltration rules.
    • style-src-attr 'unsafe-inline' is scoped strictly to element style="…" attributes needed by React SSR and live stage coordinates/transforms (F13Artwork, Player, Hud, Tour, VoiceLayer, QuizLayer). Residual Low risk: style-src-attr applies only to individual element style declarations (never stylesheets, external URLs under img-src/font-src, or script execution), and Wonderdive never passes untrusted strings into React style props.
  • frame-src isolation: App pages set frame-src ${origin}/sandbox.html, restricting framing strictly to the same-origin /sandbox.html runtime path and blocking all third-party frames and all other same-origin pages.
  • Fail-closed, defense-in-depth animation execution:
    1. Static AST/literal screening (apps/api/app/routers/animate.py, apps/api/app/jobs/verify_animation.py, skills/svg-animator/ast_screen.mjs, and apps/web/lib/sandbox.ts, plus vendored Acorn v8.19.0 inside apps/web/public/sandbox.html) rejects forbidden APIs, V8 stack-introspection escapes (prepareStackTrace, captureStackTrace, stackTraceLimit, getThis, getFunction), escaped identifiers, computed/concatenated property lookups, network/script URIs, and endless loops.
    2. Server-side fail-closed verification (apps/api/app/services/gemini/sandbox.py & verify_animation.py) executes candidate code inside an isolated node:vm context (codeGeneration: { strings: false, wasm: false }) in the pre-warmed Google DeepMind Managed-Agent sandbox (zero secrets) and requires a nonce-authenticated DOM verdict (.wonderdive/check_dom.mjs) plus in-frame bounds checks (checks_passed: ["code_screen", "acorn_ast", "sandbox_vm_frames", "dom_verdict"]). Only verified code is published to segment manifests; anything else (sandbox error, timeout, or FLAG_REMOTE_SANDBOX=off) drops animation_code / animation.url and falls back cleanly to the native vector draw-on, and "How it was made" only displays verified provenance.
    3. Client-side playback (apps/web/public/sandbox.html) runs inside <iframe sandbox="allow-scripts"> without allow-same-origin (window.origin === "null"), locks Function.prototype.constructor, shadows globals, uses a point-to-point MessageChannel port, and destroys the frame on any navigation attempt.

3. Untrusted input

Every external input (uploads, voice transcripts, animation wishes, quiz answers, nicknames, F13 SVGs, Tavily web results) is treated strictly as data, never executable instructions:

Input Risk Defence
Uploads (images, PDFs, audio) Prompt injection in PDFs, oversized payloads, malicious MIME Signed direct-to-Storage URLs (POST /v1/uploads/sign) allowlist image/{png,jpeg,webp} (≤ 10 MB), application/pdf (≤ 20 MB), audio/* (≤ 25 MB) into private uploads/<user>/<id>/<file>; PDFs analysed as <untrusted_input_data>
Voice transcripts & questions (/ask, /agent) Prompt injection, runaway renders, tool abuse Wrapped inside <untrusted_input_data> with strict JSON-schema output (extra="forbid", <= 500 chars); capped at 2 concurrent bonus renders per learner; ADK create_dive_in requires explicit tool confirmation and validates part keys / D1..Dn badges against the active lesson
Learner quiz answers (quiz-master) Prompt injection ("mark me correct") Capped at 80 chars, control chars stripped, explicit prompt-injection regex gate forces correct=False, deterministic exact-match tier before Gemini, points_ledger writable by service_role only
Shared lesson nicknames (/play/{slug}) XSS, impersonation, abuse 1..24 chars, control/invisible chars and </> rejected, multilingual + leetspeak profanity filter (apps/api/app/routers/play.py), rendered via React text nodes only, MAX_PLAYERS_PER_LESSON = 100, hidden-player moderation preserved
F13 SVGs Script/URI injection via SVG Sanitised with DOMPurify SVG profile (apps/web/lib/svg-sanitize.ts) and inside /sandbox.html (<script>, <foreignObject>, on* handlers, external href/url() stripped); local/demo asset responses set nosniff + CSP: default-src 'none'
Tavily web sources Indirect prompt injection, javascript: links Quoted as length-capped untrusted data; apps/web/components/voice/safe-url.ts permits http:// and https:// links only, rendered with rel="noopener noreferrer"

4. Rate limits and abuse controls

Every API write endpoint requires verified authentication (Depends(current_user)) and a token-bucket rate limit (apps/api/app/core/security.py, keyed by verified user:<supabase_uid> with 429 + Retry-After):

Endpoint Method Bucket Limit (per min) Burst Additional controls
/v1/uploads/sign POST uploads_sign 30 30 MIME + byte-size allowlist, private per-user Storage path
/v1/lessons POST lessons_create 10 5 F13 550 ms spacing queue (≤ 2 req/s), Gradium 2-lane pool
/v1/lessons/{lesson_id} GET lessons_read 120 40 Visibility & ownership check (private / slug-joined unlisted / public)
/v1/lessons/{lesson_id}/ask POST ask 30 10 ≤ 2 active bonus renders/learner; 10 s skill / 3 s Tavily / 8 s TTS timeouts
/v1/lessons/{lesson_id}/agent POST agent 30 10 FLAG_ADK_AGENT (on in production, 403 when off); max_llm_calls=3, per-turn tool budgets, session trimming (MAX_SESSION_EVENTS=20), ADK tool confirmation on create_dive_in
/v1/voice/token POST voice_token 60 20 Single-use, region-pinned Gradium STT token (Cache-Control: no-store)
/v1/tts POST tts 30 10 1..400 chars cap (SHORT_TTS_MAX_CHARS), Gradium 2-session pool
/v1/animate POST animate 30 10 12,000 char cap, static screen, max 2 repair attempts, 1.5 s VM timeout
/v1/lessons/{lesson_id}/parts/{part_key}/explainer POST explainer_create 12 12 Shared bucket; ≤ 2 active bonus renders/learner (429 Retry-After: 15)
/v1/lessons/{lesson_id}/explainer POST explainer_create 12 12 Shared bucket; finite bbox bounds + ≤ 2 active bonus renders/learner
/v1/lessons/{lesson_id}/explainers/{job_id} GET explainer_read 120 40 Authorized lesson check; returns status, placement, and segments
/v1/quiz/answer & /v1/quiz/{quiz_id}/answer POST quiz_answer 30 15 Shared bucket; idempotent attempt_id UUIDv5; one-time XP award per quiz
/v1/lessons/{lesson_id}/share POST lesson_share 20 8 Creator-only (owner_id == user.id); WEB_ORIGINS share URL allowlist
/v1/play/{slug}/join POST play_join 10 5 MAX_PLAYERS_PER_LESSON = 100, profanity & length checks
/v1/me/points GET me_points 60 20 Read-only sum from append-only points_ledger
/v1/lessons/{id}/leaderboard & /v1/play/{slug}/leaderboard GET lesson_leaderboard / play_leaderboard 60 20 Visitors see top 10 + me; creators see full roster
/v1/demo/* (start, ask, explainer, quiz, share, join) POST demo_* 60–120 15–30 Per-user live dive-in overlay limit (6 / min, burst 3); cached bundles immutable on disk

Scaling note: TokenBucketLimiter is thread-safe and bounded (_MAX_BUCKETS = 10,000) inside each API process (matching single-instance FastAPI Cloud deployment). Multi-replica horizontal scaling should back buckets with Redis or Postgres so rate limits stay global across workers.

5. Learner privacy (GDPR) & agent least privilege

  • Anonymous-first: Visitors join shared lessons with a classroom display name over Supabase anonymous sign-in — no email or real name required.
  • Voice ephemerality: Learner microphone audio streams over wss://eu.api.gradium.ai (configurable via GRADIUM_REGION_HOST) via single-use tokens and is never recorded or persisted. No mic access occurs on page load or on hover in Kid mode.
  • Zero model retention: GEMINI_STORE=false is enforced by default so learner prompts and uploads are not stored.

6. Security audit, GitHub Actions/CodeQL & Aikido ("Most Secure Build")

  • Automated local & CI verification results:
    • Secret guard + Gitleaks across all tracked files and git history: 0 leaked secrets.
    • Next.js production build bundle scan (.next/static & .next/server/app with server-only canary keys): 0 leaked keys or server env names; only the 3 approved NEXT_PUBLIC_* variables referenced.
    • Dependency vulnerability audit (npm audit --omit=dev on root + apps/web, pip-audit on apps/api): 0 known high/critical vulnerabilities.
    • Static analysis (CodeQL CI + Bandit): 0 high or critical findings across all production code (apps/web, apps/api, scripts).
  • GitHub Actions, CodeQL & local equivalents:
    • All workflow actions in .github/workflows/security.yml and .github/workflows/tests.yml are pinned to full 40-character commit SHAs with explicit least-privilege permissions.
    • CodeQL (javascript-typescript and python, security-and-quality query suite) runs in GitHub Actions whenever Actions are enabled on the repository; SARIF upload activates automatically once repository visibility is public, while the SARIF gate enforces zero high/critical findings on every PR.
    • Local equivalents (run anytime without GitHub Actions):
      • Secrets & history: npm run security:scan (scripts/scan-secrets.mjs --all + gitleaks)
      • Dependency audits: npm audit --omit=dev --audit-level=high (. and apps/web) and uvx pip-audit (apps/api)
      • Python static analysis: uvx bandit==1.9.4 -r apps/api/app -lll -ii
      • Next.js bundle & CSP verification: cd apps/web && npm run build + middleware header tests (npm test)
    • Prototype directory scope (labs/**): .github/workflows/codeql-config.yml excludes labs/** via paths-ignore because labs/ (zoom-theatre, f13-playground, examples, gemini-node, field-guide-landing) contains unshipped local reference prototypes that are never imported by or deployed to Vercel or FastAPI Cloud. Mark labs/ ignored/out-of-scope in the Aikido dashboard for the same reason.
  • Aikido final scan & submission screenshot:
    1. Connect the Aikido GitHub App to peresramirez/wonderdive at https://app.aikido.dev (with repo visibility set to public per hackathon rules).
    2. Trigger a full repository scan on main (Secrets, SAST, SCA, IaC, GitHub Actions) and capture the clean Aikido dashboard report screenshot for the Most Secure Build side-challenge submission.

There aren't any published security advisories