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.
- All keys live only in
.env(git-ignored,chmod 600) locally and in FastAPI Cloud / Vercel secret stores in production..env.examplelists variable names with empty placeholders only. - Every third-party vendor call (F13 Espresso, Gemini, Gradium, Tavily, and the Supabase
service_rolekey) runs strictly server-side insideapps/api. - The browser bundle (
apps/web) may read only three public values:NEXT_PUBLIC_API_BASE_URLNEXT_PUBLIC_SUPABASE_URLNEXT_PUBLIC_SUPABASE_ANON_KEY(safe only because Row-Level Security is enabled on all 13public.*tables insupabase/migrations/20261128000200_rls_and_views.sqland20261128180000_unlisted_by_slug.sql)
- Feature flags are fetched at runtime from
GET /v1/health(never viaNEXT_PUBLIC_FLAG_*env vars). - Browser microphone sessions never touch
GRADIUM_API_KEY;POST /v1/voice/tokenissues a short-lived, single-use, region-pinned Gradium STT token alongside its matchingws_url(wss://eu.api.gradium.ai/api/speech/asrby default, withCache-Control: no-store), andapps/web/lib/gradium-mic.tsexplicitly rejects rawgsk_*keys. apps/api/app/core/config.pyinstallsSecretRedactingFilteracross every Python logger andapps/api/app/core/logging.pyscrubs 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_roleJWTs, and exact values from your local.env) +gitleaks git --pre-commit --staged..githooks/pre-push: runs the secret guard andgitleaksover all files and the entire git history.- GitHub Actions CI (
.github/workflows/security.yml, every action pinned to a 40-char commit SHA, minimalcontents: readpermissions by default):- Secrets & history:
scripts/scan-secrets.mjs --all+ SHA-256 checksum-verifiedgitleaks(v8.30.1) over the full git history. - Hygiene: verifies zero git-ignored files are tracked,
apps/websource references no server secret names and only the 3 allowedNEXT_PUBLIC_*vars, and every write route inapps/api/app/routersenforcesDepends(current_user)+rate_limit(...). - Next.js bundle & CSP header verification: runs
next buildwith server-only canary secrets injected into the build environment, scans.next/staticand.next/server/appto verify zero server canaries, vendor keys,service_roleJWTs, or extraNEXT_PUBLIC_*variables enter the bundle, and bootsnext startto verify live HTTP security headers and CSP on/and/sandbox.html. - Dependency audit:
npm audit --omit=dev --audit-level=high(.andapps/web) +pip-audit(apps/api), backed by weekly.github/dependabot.ymlupdates. - SAST (CodeQL + Bandit): CodeQL (
javascript-typescriptandpython,security-and-qualityquery suite) parses SARIF output and fails the workflow on any high/critical security finding (security-severity >= 7.0or error-level security alert), uploading SARIF to GitHub Code Scanning automatically when repository visibility ispublic.bandit(-lll -ii) additionally runs high-severity Python SAST acrossapps/api/app.
- Secrets & history:
- 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).
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.tsmints a fresh 128-bit Web Crypto CSPRNG base64 nonce (generateCspNonce()) on every app request, forwards bothx-nonceandContent-Security-Policyon the request headers, and sets the matchingContent-Security-Policyresponse header.apps/web/app/layout.tsxreadsx-nonceviaawait 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 anydata-*attribute).'strict-dynamic'is intentionally omitted so'self'remains enforced for Next.js chunks andaudioWorklet.addModule('/worklets/pcm-processor.js').- Static documents:
/pitch(/pitch-deck.htmlinpublic/) stays a static standalone HTML presentation and avoids'unsafe-inline'on bothscript-srcandstyle-srcvia SHA-256 hashes of every inline<script>and<style>block computed automatically frompublic/pitch-deck.htmlat build time inapps/web/next.config.mjs(so edits to the deck never drift from its CSP)./sandbox.htmlstays a static document loaded exclusively inside<iframe sandbox="allow-scripts">(noallow-same-origin, sowindow.origin === "null") withdefault-src 'none'; connect-src 'none'; frame-ancestors 'self'. It retainsscript-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-srcdisallows'unsafe-inline'in production (style-src 'self' 'nonce-<base64>'plus the build-time SHA-256 hash of Next.js's built-in 404HTTPAccessErrorFallback<style>tag extracted fromnextinapps/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 elementstyle="…"attributes needed by React SSR and live stage coordinates/transforms (F13Artwork,Player,Hud,Tour,VoiceLayer,QuizLayer). Residual Low risk:style-src-attrapplies only to individual element style declarations (never stylesheets, external URLs underimg-src/font-src, or script execution), and Wonderdive never passes untrusted strings into Reactstyleprops.
frame-srcisolation: App pages setframe-src ${origin}/sandbox.html, restricting framing strictly to the same-origin/sandbox.htmlruntime path and blocking all third-party frames and all other same-origin pages.- Fail-closed, defense-in-depth animation execution:
- Static AST/literal screening (
apps/api/app/routers/animate.py,apps/api/app/jobs/verify_animation.py,skills/svg-animator/ast_screen.mjs, andapps/web/lib/sandbox.ts, plus vendored Acorn v8.19.0 insideapps/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. - Server-side fail-closed verification (
apps/api/app/services/gemini/sandbox.py&verify_animation.py) executes candidate code inside an isolatednode:vmcontext (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, orFLAG_REMOTE_SANDBOX=off) dropsanimation_code/animation.urland falls back cleanly to the native vector draw-on, and "How it was made" only displays verified provenance. - Client-side playback (
apps/web/public/sandbox.html) runs inside<iframe sandbox="allow-scripts">withoutallow-same-origin(window.origin === "null"), locksFunction.prototype.constructor, shadows globals, uses a point-to-pointMessageChannelport, and destroys the frame on any navigation attempt.
- Static AST/literal screening (
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" |
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:
TokenBucketLimiteris 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.
- 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 viaGRADIUM_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=falseis enforced by default so learner prompts and uploads are not stored.
- 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/appwith server-only canary keys): 0 leaked keys or server env names; only the 3 approvedNEXT_PUBLIC_*variables referenced. - Dependency vulnerability audit (
npm audit --omit=devon root +apps/web,pip-auditonapps/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.ymland.github/workflows/tests.ymlare pinned to full 40-character commit SHAs with explicit least-privilegepermissions. - CodeQL (
javascript-typescriptandpython,security-and-qualityquery suite) runs in GitHub Actions whenever Actions are enabled on the repository; SARIF upload activates automatically once repository visibility ispublic, 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(.andapps/web) anduvx 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)
- Secrets & history:
- Prototype directory scope (
labs/**):.github/workflows/codeql-config.ymlexcludeslabs/**viapaths-ignorebecauselabs/(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. Marklabs/ignored/out-of-scope in the Aikido dashboard for the same reason.
- All workflow actions in
- Aikido final scan & submission screenshot:
- Connect the Aikido GitHub App to
peresramirez/wonderdiveat https://app.aikido.dev (with repo visibility set topublicper hackathon rules). - 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.
- Connect the Aikido GitHub App to