1. Front Matter
Title: Embed HTML Content in Quest Nodes ([3.9])
Author: Joshua Uriel Tribiana — original author (2026-06-29)
Updated by: Patrick Babala — author of PR #870 (learner Code-block sandbox / XSS fix)
Reviewers: JD Billate (zcrnnn) — original review. Update review: Christian Denzon (@cdnzn) (reviewed PR #870); Clyde Ador (@clydetims) authored the sanitisation/sandbox work in PR #666 and Christian Denzon authored the hardening in PR #884, both merged by the updater.
Created: 2026-06-29
Updated: 2026-09-30
Status: Published (feature live)
References:
Issue: [3.9] Embed HTML Custom Node — the original guide listed this label with no issue number or link; no numbered parent issue is recorded. Corrected in 2.0.
Related security issues: #844 XSS in learner code-block renderer; #861 HTML sanitizer / iframe sandbox.
Update PRs covered by this revision: #398 original Code/HTML node feature; #666 HTML-node sanitisation and sandbox; #870 learner code-block XSS fix (
SandboxedHtmlFrame); #884 sanitizer and iframe-sandbox hardening.Related guides (do not duplicate): Visual Canvas ([2.2]) owns the CodeBlock node's canvas placement, fullscreen, language detection, and the 50,000-character limit (PRs #708 / #712); Form Editor ([2.1]) owns the
codeblockcontent card. Link-node provider embeds (PR #798) are a separate feature.
2. Introduction & Goals
Problem Summary
Creators need a way to include rich, interactive, or custom-styled content directly within a quest. This feature lets creators embed custom HTML, CSS, and limited interactivity, enabling experiences like interactive simulations, embedded forms, or unique content layouts that are not possible with the standard node types. The primary technical challenge is enabling that flexibility while preventing Cross-Site Scripting (XSS), especially when quests are shared publicly.
Goals
Provide an HTML-content node in the Visual Canvas editor. Corrected in 2.0: the shipped UI label is "Code Block" and the node type is
Code(lib/utils/nodeTypes.tsx:29,components/quest-editor/visual-canvas/nodes/CodeNode.tsx:352), not "HTML Node".Integrate a code editor (Monaco Editor) for an improved authoring experience — shipped (
CodeNode.tsx:78).Sanitize HTML before it is rendered. Corrected in 2.0: sanitization is performed client-side at render time by
sanitizeHtml()(lib/utils/sanitize-html.ts), not server-side with DOMPurify on save. The server never sanitizes or rewritescodeContent.Render learner HTML inside a sandboxed
<iframe>to isolate it from the main application — shipped viaSandboxedHtmlFrame(components/learner/renderers/SandboxedHtmlFrame.tsx:184).Enforce a 50,000-character limit on the HTML content — shipped in three places: the Zod schema (
lib/schemas/nodes.schema.ts:96), the save API (app/api/creator/update-quest-canvas/route.ts:121-133), and the editor UI (CodeNode.tsx:148-149,522-532).Set a
Content-Security-Policyheader on public share pages. Corrected in 2.0: not implemented. NoContent-Security-Policy,frame-ancestors, orX-Frame-Optionsheader exists inmiddleware.tsor anywhere else in the codebase. The sandboxed iframe is the implemented containment.
Non-Goals
Execution of server-side code (e.g., PHP). This is a client-side-only feature.
Direct access to the parent page's DOM, cookies, or
localStorage— enforced by the sandbox.Hosting assets (images, scripts) referenced in the HTML; creators must use absolute URLs.
A full-fledged IDE experience within the node.
Corrected in 2.0 (behaviour change): the original rendering workflow implied limited JavaScript support. In the shipped learner path, creator-authored
<script>tags and event-handler attributes are stripped; only the creator's own editor preview executes scripts. See section 4.Glossary
Code Block node (original: "HTML Node"): The Visual Canvas node type (
Code) for embedding custom HTML.Sanitization: Cleaning creator HTML to remove dangerous code (
<script>,on*handlers,javascript:URLs) before it is stored or rendered.Sandboxed
<iframe>: An<iframe>whosesandboxattribute restricts it from running scripts that reach the app origin, navigating the top frame, or reading cookies/storage.XSS (Cross-Site Scripting): Injecting malicious script into otherwise trusted content.
srcDocframe: The learner rendering technique — sanitized HTML is written into the iframe'ssrcdoc, so no external document is fetched.
3. High-Level Architecture
System Diagram
Technologies Used
Next.js (App Router) / TypeScript — route handlers and UI.
React Flow (
@xyflow/react) — Visual Canvas that hosts theCodenode.Monaco Editor (
@monaco-editor/react) — code editing in the creator (CodeNode.tsx) and in the learner outline renderer (CodeblockRenderer.tsx).Zod — payload/schema validation (
codeNodeDataSchema,updateCanvasSchema→canvasMetadataSchema).Supabase (Postgres + Auth) — persists
quests.canvas_metadata(JSONB) andquest_content_cards; authoring uses Supabase Auth.Custom HTML sanitizer (no external dependency) —
lib/utils/sanitize-html.ts.
Corrected in 2.0: the original guide listed DOMPurify as the sanitizer and "Next.js for setting security headers". Neither is true for this feature.
dompurifyandisomorphic-dompurifyare present inpackage.json, but they are used elsewhere (Text nodes incomponents/learner/QuestContentRenderer.tsx:19,ReflectionRenderer.tsx, and the forum) — not by the Code-node render path. No CSP header is set.Component Overview / Key Data Flow
Creator (Visual Canvas) Learner (two surfaces)+---------------------------+ +---------------------------------------+| Code Block node | | QuestContentRenderer -> CodeblockRenderer || Monaco editor (.codeContent) | or || Preview: sanitize(allow- | | quest-detail -> CodeblockCardContent || Scripts:true) + execute | | | |+-------------+-------------+ | SandboxedHtmlFrame (srcdoc iframe, || debounced autosave | LEARNER_CONTENT_SANDBOX, theme tokens) |v +---------------------------------------+PUT /api/creator/update-quest-canvas ^- zod validate | sanitizeHtml(allowScripts:false)- 50k length guard -> HTTP 400 |- hasMeaningfulCanvasChange -> draft |- NO sanitization ------------------------------+ |v | |quests.canvas_metadata (JSONB) -- mirror --> quest_content_cards (codeblock/content.html)
4. Detailed Design & Implementation
Data Model / Schema
No new tables are required. The feature adds a
codeContentstring to thedataobject of theCodenode insidequests.canvas_metadata(JSONB), and (for linear mode) mirrors it into acodeblockcontent card.Property
Type
Constraints
Where
codeContentstringmax(50000)lib/schemas/nodes.schema.ts:96(codeNodeDataSchema)codeLanguagestring?optional
set by canvas sync (
lib/canvas-sync/formToCanvas.ts:261)label,audio_url,isFullscreen,stylingVariant,isArchived, …—
inherited
Codenode fieldslib/schemas/nodes.schema.ts:92-114Database columns:
quests.canvas_metadata(JSONB, pre-existing) andquest_content_cards.content(JSONB,type = 'codeblock',content.html). No migration was added by this feature and none exists for it insupabase/migrations.Example node JSON:
{"id": "node-html-456","type": "Code","position": { "x": 250, "y": 150 },"data": {"label": "Interactive Simulation","codeContent": "<style>...</style><div>...</div>"}}Corrected in 2.0: the original table described
codeContentas "the sanitized HTML content". It is stored exactly as authored; sanitization happens only when the learner render copies it into the iframesrcDoc.API Specification
The feature reuses the existing canvas-update endpoint. It is a length guard only — there is no sanitization middleware.
Endpoint:
PUT /api/creator/update-quest-canvas(app/api/creator/update-quest-canvas/route.ts:103)Auth:
getCreatorAuthContext()+verifyAgencyResourceOwnership()(:106,:154)Validation:
updateCanvasSchema→canvasMetadataSchema(:110)Implementation (
:121-133): iteratescanvas_metadata.nodes; for anynode.type === "Code"whosecodeContent.length > 50000, it returnsApiResponseHelper.validationError(...)— i.e. HTTP 400 with the node label and character count. Content is not truncated and not sanitized; the request is rejected.Side effect:
hasMeaningfulCanvasChangereverts a published quest to draft on canvas mutation (:21).
Corrected in 2.0: the original spec said the handler "truncates to 50,000 and passes the content through
DOMPurify.sanitize(), replacingcodeContentbefore save". That code does not exist. The real handler rejects oversize input and stores everything else verbatim.Logic & Workflows
Authoring workflow (creator)
The creator drags the Code Block node onto the Visual Canvas (
lib/utils/nodeTypes.tsx:29).CodeNode.tsxmountsMemoizedMonacoEditorwithdefaultLanguage="html"(:78-104), loadingdata.codeContent.Templates: the Code button opens
HTML_TEMPLATES(9 templates — Iframe Embed, HTML5 Video, Simple Contact Form, Survey Form, Accordion, Tabs, Timeline, Progress Bar, Info Box;lib/utils/html-templates.ts). Appending a template callsconfirmPublishedEdit()first.Preview toggle (
:242-257): sanitizes with{ allowScripts: true, allowIframes: true, allowSvg: true }, thenmarkContainerForScripts(previewRef.current)+executeHtmlWithScripts(previewRef.current, sanitized). This is the only place this feature executes creator scripts.Auto-save (
:155-197): a 5-second timer writeslastSavedAt; the canvas-level debounced save persists the wholecanvas_metadata.50k guard (
:148-149,:522-532): a counter showsn/50000; above 45,000 a warning appears; above 50,000 auto-save pauses and the counter turns red — and the server would reject the save anyway.
Script execution helper (
lib/utils/execute-html-with-scripts.ts)executeHtmlWithScripts(container, codeContent)(:79) extracts external and inline<script>blocks, injects the remaining HTML, loads external scripts once (deduped byloadedScripts), waits up to 3 s for thed3global, then re-injects inline scripts inside an IIFE targeting[data-template-container] || document.body.markContainerForScripts(el)(:137) setsdata-template-container="true"so inline scripts target the right node.
Used only by the creator preview. No learner component imports it.
Canvas ⇄ Form synchronization
canvasToFormmapsCode/Codeblock→codeblockcards with{ html: contentData.codeContent, title, audio_url }(lib/canvas-sync/canvasToForm.ts:100-106, 242-245, 313-318).formToCanvasmapscodeblock→Codenodes with{ codeContent: card.content.html, codeLanguage: card.data.language }(lib/canvas-sync/formToCanvas.ts:259-262, 460-464).
Rendering workflow (learner)
There are two learner surfaces, and both funnel into the same frame:
Canvas / child-node path:
QuestContentRenderer.tsx:183-193renders<CodeblockRenderer>forchild.type === "Code".CodeblockRenderer(components/learner/renderers/CodeblockRenderer.tsx) shows a read view of the code withdetectLanguage()(:16-47), a Preview toggle, and an/50,000counter; Preview renders<SandboxedHtmlFrame html={code} …/>(:147-151).Quest-detail content-card path:
components/learner/quest-detail/content-cards/CodeblockCardContent.tsx:35-40renders<SandboxedHtmlFrame html={card.content.html} …/>directly (with thecodeblockcard's optional background audio).
SandboxedHtmlFrame(components/learner/renderers/SandboxedHtmlFrame.tsx):Builds
srcDoc= a<style>block (theme tokens + base styles) followed bysanitizeHtml(html, { allowScripts: false, allowIframes: true, allowSvg: true })(:143-153).Renders
<iframe srcDoc={…} sandbox={LEARNER_CONTENT_SANDBOX} loading="lazy">(:181-190), whereLEARNER_CONTENT_SANDBOX = "allow-scripts allow-forms allow-popups"— deliberately withoutallow-same-origin, so content runs in an opaque origin and cannot reach the app origin, cookies, storage, or the parent document.Copies a safe subset of the parent's CSS custom properties (
--theme-*,--font-*,--border, …) into the frame via a sharedMutationObserver, validating names (SAFE_VARIABLE_NAME) and rejecting values containing<,>, or}(:37-141). Because the frame has no same-origin access, tokens must be copied in; the app stylesheet does not cross the boundary.
Corrected in 2.0: the original guide's sandbox example (
allow-forms allow-modals allow-popups allow-presentation) and its claim that scripts are "prevented" only by the sandbox are both inaccurate. Learner content does receiveallow-scripts(so legitimately embedded third-party iframes still work), but the sanitizer removes the creator's<script>/handlers before they ever reach the frame. The isolation comes from omittingallow-same-origin, not from omittingallow-scripts.Security boundary —
lib/utils/sanitize-html.tsA dependency-free, DOMParser-based allow-list sanitizer.
Tag allow-list
ALLOWED_TAGS(:26-49): structural, media, form, SVG, table, and semantic tags, plusstyle.<script>is deliberately absent; a bare<script>node is removed entirely (never unwrapped into live markup) unlessallowScriptsis set (:203-207). Disallowed wrapper tags are unwrapped and their relocated descendants re-queued in the same pass (:208-220).Attribute allow-list (
:55-85): per-tag sets plusclass/id/style/title/alt/roleanddata-*/aria-*.Dangerous protocols (
:87, :118-130, :237-247):javascript:,data:,vbscript:are stripped fromhref,src,action, andposter.iframe sandbox forced (
:249-252): every surviving<iframe>is rewritten tosandbox="allow-scripts allow-same-origin allow-forms allow-popups"(DEFAULT_IFRAME_SANDBOX) regardless of the authored value.Length (
:144-150):maxContentLengthdefaults to 50,000 and is applied to the string before parsing.Server fallback (
:268-286): whenDOMParseris unavailable, a regex-based pass strips scripts/handlers and dangerous protocols.Exports:
sanitizeHtml,stripHtmlTags,createIframeSandbox(allowScripts),isHtmlSafe,DEFAULT_IFRAME_SANDBOX,LEARNER_CONTENT_SANDBOX.
createIframeSandbox(:298-311) is used only by the public-share embed snippet (components/quest-editor/public-share-modal/Embed.tsx:45) to sandbox quests embedded on external sites — related, but distinct from the Code-node frame.Documented in 2.0:
isHtmlSafe(:316) is exported but unused in the app (referenced only by its unit test); itsdata:heuristic was narrowed to allow common base64 image types.Branching API (documented, currently unwired)
lib/utils/branching-integration.tsdefineswindow.wyzQuests.{makeDecision, submitForm, advanceNode}viainitializeBranchingAPI/attachGlobalBranchingAPI/setupWyzQuestsIntegration(:31,:128,:278), plusgetFormData,createFormSubmitHandler,createDecisionClickHandler,ValidationRules, andLogger. TheCodeNodeUI advertises this to creators (CodeNode.tsx:534-541), but no module importsbranching-integration.ts— nothing installswindow.wyzQuests, so interactive branching from an embedded HTML node does not currently work. This is a real limitation, not a documentation gap.Key Files
components/quest-editor/visual-canvas/nodes/CodeNode.tsx— creator-facing node: Monaco editor, preview, templates, 50k guard, autosave.lib/utils/sanitize-html.ts— the sanitizer and sandbox constants.lib/utils/execute-html-with-scripts.ts— creator-preview script execution.lib/utils/html-templates.ts— 9 starter templates.lib/utils/branching-integration.ts— advertisedwindow.wyzQuestshelper (unwired).lib/schemas/nodes.schema.ts—codeNodeDataSchema(50k).app/api/creator/update-quest-canvas/route.ts— PUT/GET canvas; 50k server guard.lib/canvas-sync/canvasToForm.ts,lib/canvas-sync/formToCanvas.ts—Code⇄codeblockmapping.components/learner/renderers/SandboxedHtmlFrame.tsx— learner iframe (srcDoc, sandbox, theme tokens).components/learner/renderers/CodeblockRenderer.tsx— learner canvas-node renderer.components/learner/quest-detail/content-cards/CodeblockCardContent.tsx— learner content-card renderer.components/learner/QuestContentRenderer.tsx— dispatchesCode→CodeblockRenderer.components/quest-editor/public-share-modal/Embed.tsx— public-share embed sandbox snippet.
Corrected in 2.0: the original guide referenced
lib/security/html-sanitizer.service.tsandcomponents/learner/player/nodes/RenderHtmlNode.tsx; neither file exists. It also saidmiddleware.ts"to be updated" for CSP — no such change was ever made.
5. Infrastructure & Operations
Dependencies
Internal: existing quest editor, canvas-sync, and learner player infrastructure. No new tables.
External: the sanitizer has no runtime dependency.
@monaco-editor/reactis used for editing;dompurify/isomorphic-dompurifyexist in the project but are not part of this feature's render path.
Corrected in 2.0: the original deployment plan said to "add
dompurifyandjsdomtopackage.json". No dependency was added for this feature, and nojsdomwas introduced.Monitoring & Alerting
Standard monitoring for
PUT /api/creator/update-quest-canvasapplies. Corrected in 2.0: the original recommendation to "log an event whenever the sanitization service strips content" was never implemented — the sanitizer is a pure client-side function with no telemetry, so stripped content is currently not observable server-side. If abuse monitoring is required, it must be added (e.g. report sanitizer stats to an endpoint).Deployment Plan
Rollout: shipped directly through PRs #398 → #666 → #870 → #884. Corrected in 2.0: the original recommended a phased, feature-flagged rollout "because this feature poses a security risk if misconfigured"; no feature flag was added.
Security posture: containment on the learner side is the sandboxed, same-origin-less iframe plus the sanitizer. There is no CSP header and no server-side sanitization, contrary to the original plan.
6. Testing & Quality Assurance
Test Strategy
Unit tests
tests/unit/sanitize-html.test.ts— strips<script>and handler attributes; drops script contents (no unwrap-as-text); retains scripts only withallowScripts: true; enforces iframesandbox; stripsjavascript:fromhref; sanitizes descendants of disallowed wrappers; strips dangerousaction/poster; server fallback path;LEARNER_CONTENT_SANDBOXomitsallow-same-origin; theaccordion/tabstemplates ship no scripts/handlers;details/checkedattributes survive;isHtmlSafecases.tests/unit/codeblock-card-sandbox.test.tsx—CodeblockCardContentrenders the content in an iframe whosesandboxequalsLEARNER_CONTENT_SANDBOX(noallow-same-origin), and a<script>probe never reachessrcdocor the app document.
Integration / E2E
tests/e2e/creator/embed-html.spec.ts— QA-049: add a Code Block node, type/paste HTML, verify the Monaco editor, live preview, char counter, and auto-save. QA-050: paste an XSS payload (onerror,javascript:iframe) and assert no dialog fires and noiframe[src*="javascript:"]exists.No automated test covers the API's 50k guard, and there is no server-sanitization test (because there is no server sanitization).
Corrected in 2.0: the original Test Strategy described unit tests for
html-sanitizer.service.tsand an integration test asserting "the data stored is the sanitized version". Those tests/files do not exist. The tests that exist test the client sanitizer and the learner frame.SEC-4 (XSS) — the original referenced
FEATURE_AUDIT_MAY2026.mdfor the XSS risk. That audit's row 3.9 Embed HTML Custom Node (docs/FEATURE_AUDIT_MAY2026.md:87) is now satisfied: sanitisation and the 50k limit are both enforced (client sanitizer + server length guard), and the learner frame is sandboxed.Known Limitations
Corrected in 2.0: the original guide's headline limitation — "the current implementation is missing the sanitization and character limit enforcement, which is a critical security risk" — is resolved. The expected-implementation caveat no longer applies. Current, real limitations:
Creator scripts do not run for learners — they are stripped by
sanitizeHtml({ allowScripts: false }); only the creator preview executes them (CodeNode.tsx). Content that relies on inline JS (oronclick) will render inertly for learners.No CSP / security headers are set (see sections 2 and 5).
No server-side sanitization or telemetry; the raw HTML is stored as authored.
isHtmlSafeis unused in the app.The
window.wyzQuestsbranching API is unwired (see section 4).Theme tokens are a subset — only listed
--theme-*/--font-*/etc. prefixes are copied into the frame; arbitrary app CSS variables are not.Public-share embed sandbox (
Embed.tsx) is separate and governed bycreateIframeSandbox.
7. Maintenance & Support
Troubleshooting
Embedded content renders unstyled / different from the editor: expected — the learner frame is isolated. Only the token subset in
SandboxedHtmlFrame.tsx(CONTENT_VARIABLE_PREFIXES) crosses into the frame; app stylesheets do not.Content renders but is missing tags/attributes: the allow-list stripped them. Check
ALLOWED_TAGS/WHITELISTED_ATTRIBUTESinlib/utils/sanitize-html.ts.Creator's JavaScript "does not work" for learners: intended. Inline scripts and
on*handlers are removed for learners; only third-party iframes' own scripts run (the frame allows scripts but not same-origin). Explain the security rationale.A script works in Preview but not in the learner view: that is the design (
CodeNode.tsxpreview opts intoallowScripts; the learner frame does not).Save rejected with a 50,000-character error: the server returns HTTP 400 (
ApiResponseHelper.validationError) with the node label and count. ReducecodeContent; the client also pauses auto-save above the limit.iframecontent blocked / navigation errors: the iframe is force-set toDEFAULT_IFRAME_SANDBOXand the learner frame omitsallow-same-origin; check the browser console for sandbox errors and confirm the embed's own origin allows framing.Branching from an HTML button does nothing:
window.wyzQuestsis never installed (branching-integration is unwired). The Code node's hint is currently misleading.
Changelog
v1.0 (2026-06-29) — Approved; technical guide created describing the required, secure implementation (server-side DOMPurify + CSP).
v2.0 (2026-09-30) — Updated by Patrick Babala. See the Document version entry below.
Document version
2.0 — Updated by Patrick Babala, 2026-09-30. Overhauled to match the code that actually shipped:
Corrected the central premise: sanitization is client-side in
lib/utils/sanitize-html.ts, not server-side DOMPurify; the API is a 50k length guard only (HTTP 400, no truncation/no sanitize).Corrected file references: removed non-existent
lib/security/html-sanitizer.service.tsandcomponents/learner/player/nodes/RenderHtmlNode.tsx; addedSandboxedHtmlFrame.tsx,CodeblockRenderer.tsx,CodeblockCardContent.tsx,execute-html-with-scripts.ts,html-templates.ts.Removed the false middleware CSP claim (no CSP/
X-Frame-Optionsanywhere).Documented the real script/sandbox behaviour: creator preview executes scripts; learner content is stripped and rendered in
LEARNER_CONTENT_SANDBOX(noallow-same-origin).Documented the unwired
window.wyzQuestsbranching API.Marked the original "missing sanitization" Known Limitation as resolved; re-verified coverage against
sanitize-html.test.ts,codeblock-card-sandbox.test.tsx, andembed-html.spec.ts(QA-049 / QA-050).Redrew the system diagram as a layered architecture from code.
Linked the real update PRs: #398 (original), #666 (sanitisation/sandbox), #870 (learner sandbox, updater's PR), #884 (hardening).
1.0 — Approved, technical guide created for secure implementation, 2026-06-29 (author: Uriel / Joshua Uriel Tribiana).