Embed HTML Custom Node

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 codeblock content 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 rewrites codeContent.

    • Render learner HTML inside a sandboxed <iframe> to isolate it from the main application — shipped via SandboxedHtmlFrame (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-Policy header on public share pages. Corrected in 2.0: not implemented. No Content-Security-Policy, frame-ancestors, or X-Frame-Options header exists in middleware.ts or 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> whose sandbox attribute 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.

    • srcDoc frame: The learner rendering technique — sanitized HTML is written into the iframe's srcdoc, 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 the Code node.

    • 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) and quest_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. dompurify and isomorphic-dompurify are present in package.json, but they are used elsewhere (Text nodes in components/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 codeContent string to the data object of the Code node inside quests.canvas_metadata (JSONB), and (for linear mode) mirrors it into a codeblock content card.

    Property

    Type

    Constraints

    Where

    codeContent

    string

    max(50000)

    lib/schemas/nodes.schema.ts:96 (codeNodeDataSchema)

    codeLanguage

    string?

    optional

    set by canvas sync (lib/canvas-sync/formToCanvas.ts:261)

    label, audio_url, isFullscreen, stylingVariant, isArchived, …

    —

    inherited Code node fields

    lib/schemas/nodes.schema.ts:92-114

    Database columns: quests.canvas_metadata (JSONB, pre-existing) and quest_content_cards.content (JSONB, type = 'codeblock', content.html). No migration was added by this feature and none exists for it in supabase/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 codeContent as "the sanitized HTML content". It is stored exactly as authored; sanitization happens only when the learner render copies it into the iframe srcDoc.

  • 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): iterates canvas_metadata.nodes; for any node.type === "Code" whose codeContent.length > 50000, it returns ApiResponseHelper.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: hasMeaningfulCanvasChange reverts 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(), replacing codeContent before save". That code does not exist. The real handler rejects oversize input and stores everything else verbatim.

  • Logic & Workflows

    Authoring workflow (creator)

    1. The creator drags the Code Block node onto the Visual Canvas (lib/utils/nodeTypes.tsx:29).

    2. CodeNode.tsx mounts MemoizedMonacoEditor with defaultLanguage="html" (:78-104), loading data.codeContent.

    3. 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 calls confirmPublishedEdit() first.

    4. Preview toggle (:242-257): sanitizes with { allowScripts: true, allowIframes: true, allowSvg: true }, then markContainerForScripts(previewRef.current) + executeHtmlWithScripts(previewRef.current, sanitized). This is the only place this feature executes creator scripts.

    5. Auto-save (:155-197): a 5-second timer writes lastSavedAt; the canvas-level debounced save persists the whole canvas_metadata.

    6. 50k guard (:148-149, :522-532): a counter shows n/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 by loadedScripts), waits up to 3 s for the d3 global, then re-injects inline scripts inside an IIFE targeting [data-template-container] || document.body.

    • markContainerForScripts(el) (:137) sets data-template-container="true" so inline scripts target the right node.

    Used only by the creator preview. No learner component imports it.

    Canvas ⇄ Form synchronization

    • canvasToForm maps Code / Codeblock → codeblock cards with { html: contentData.codeContent, title, audio_url } (lib/canvas-sync/canvasToForm.ts:100-106, 242-245, 313-318).

    • formToCanvas maps codeblock → Code nodes 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:

    1. Canvas / child-node path: QuestContentRenderer.tsx:183-193 renders <CodeblockRenderer> for child.type === "Code". CodeblockRenderer (components/learner/renderers/CodeblockRenderer.tsx) shows a read view of the code with detectLanguage() (:16-47), a Preview toggle, and a n/50,000 counter; Preview renders <SandboxedHtmlFrame html={code} …/> (:147-151).

    2. Quest-detail content-card path: components/learner/quest-detail/content-cards/CodeblockCardContent.tsx:35-40 renders <SandboxedHtmlFrame html={card.content.html} …/> directly (with the codeblock card's optional background audio).

    SandboxedHtmlFrame (components/learner/renderers/SandboxedHtmlFrame.tsx):

    • Builds srcDoc = a <style> block (theme tokens + base styles) followed by sanitizeHtml(html, { allowScripts: false, allowIframes: true, allowSvg: true }) (:143-153).

    • Renders <iframe srcDoc={…} sandbox={LEARNER_CONTENT_SANDBOX} loading="lazy"> (:181-190), where LEARNER_CONTENT_SANDBOX = "allow-scripts allow-forms allow-popups" — deliberately without allow-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 shared MutationObserver, 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 receive allow-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 omitting allow-same-origin, not from omitting allow-scripts.

    Security boundary — lib/utils/sanitize-html.ts

    A dependency-free, DOMParser-based allow-list sanitizer.

    • Tag allow-list ALLOWED_TAGS (:26-49): structural, media, form, SVG, table, and semantic tags, plus style. <script> is deliberately absent; a bare <script> node is removed entirely (never unwrapped into live markup) unless allowScripts is 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 plus class/id/style/title/alt/role and data-*/aria-*.

    • Dangerous protocols (:87, :118-130, :237-247): javascript:, data:, vbscript: are stripped from href, src, action, and poster.

    • iframe sandbox forced (:249-252): every surviving <iframe> is rewritten to sandbox="allow-scripts allow-same-origin allow-forms allow-popups" (DEFAULT_IFRAME_SANDBOX) regardless of the authored value.

    • Length (:144-150): maxContentLength defaults to 50,000 and is applied to the string before parsing.

    • Server fallback (:268-286): when DOMParser is 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); its data: heuristic was narrowed to allow common base64 image types.

    Branching API (documented, currently unwired)

    lib/utils/branching-integration.ts defines window.wyzQuests.{makeDecision, submitForm, advanceNode} via initializeBranchingAPI / attachGlobalBranchingAPI / setupWyzQuestsIntegration (:31, :128, :278), plus getFormData, createFormSubmitHandler, createDecisionClickHandler, ValidationRules, and Logger. The CodeNode UI advertises this to creators (CodeNode.tsx:534-541), but no module imports branching-integration.ts — nothing installs window.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 — advertised window.wyzQuests helper (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 ⇄ codeblock mapping.

    • 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 — dispatches Code → 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.ts and components/learner/player/nodes/RenderHtmlNode.tsx; neither file exists. It also said middleware.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/react is used for editing; dompurify / isomorphic-dompurify exist in the project but are not part of this feature's render path.

    Corrected in 2.0: the original deployment plan said to "add dompurify and jsdom to package.json". No dependency was added for this feature, and no jsdom was introduced.

  • Monitoring & Alerting

    Standard monitoring for PUT /api/creator/update-quest-canvas applies. 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 with allowScripts: true; enforces iframe sandbox; strips javascript: from href; sanitizes descendants of disallowed wrappers; strips dangerous action/poster; server fallback path; LEARNER_CONTENT_SANDBOX omits allow-same-origin; the accordion/tabs templates ship no scripts/handlers; details/checked attributes survive; isHtmlSafe cases.

    • tests/unit/codeblock-card-sandbox.test.tsx — CodeblockCardContent renders the content in an iframe whose sandbox equals LEARNER_CONTENT_SANDBOX (no allow-same-origin), and a <script> probe never reaches srcdoc or 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 no iframe[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.ts and 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.md for 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 (or onclick) 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.

    • isHtmlSafe is unused in the app.

    • The window.wyzQuests branching 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 by createIframeSandbox.

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_ATTRIBUTES in lib/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.tsx preview opts into allowScripts; 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. Reduce codeContent; the client also pauses auto-save above the limit.

    • iframe content blocked / navigation errors: the iframe is force-set to DEFAULT_IFRAME_SANDBOX and the learner frame omits allow-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.wyzQuests is 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.ts and components/learner/player/nodes/RenderHtmlNode.tsx; added SandboxedHtmlFrame.tsx, CodeblockRenderer.tsx, CodeblockCardContent.tsx, execute-html-with-scripts.ts, html-templates.ts.

      • Removed the false middleware CSP claim (no CSP/X-Frame-Options anywhere).

      • Documented the real script/sandbox behaviour: creator preview executes scripts; learner content is stripped and rendered in LEARNER_CONTENT_SANDBOX (no allow-same-origin).

      • Documented the unwired window.wyzQuests branching API.

      • Marked the original "missing sanitization" Known Limitation as resolved; re-verified coverage against sanitize-html.test.ts, codeblock-card-sandbox.test.tsx, and embed-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).


Was this article helpful?