Files
site-builder/craft/src/components/basic/HtmlBlock.tsx
T

205 lines
10 KiB
TypeScript
Raw Normal View History

import React, { CSSProperties, useMemo } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import DOMPurify from 'dompurify';
interface HtmlBlockProps {
code: string;
style?: CSSProperties;
aiName?: string;
node_id?: string;
}
// Task 24: widening the allow-list after a customer's broad HTML fixture
// showed 38% of it silently deleted (tables losing colspan/rowspan/scope,
// <dl>/<sub>/<details>/inline <svg>/<video>/<audio> dropped wholesale,
// lang/dir/role stripped, <ol start/reversed> flattened). The owner's call:
// be generous -- this block is an explicit escape hatch and customers
// reasonably expect it to render ordinary HTML, including forms. The four
// non-negotiables (no <script>, no on*, no javascript: URLs, iframes stay
// sandboxed) are unaffected by the widening and are covered by dedicated
// tests in HtmlBlock.test.ts / HtmlBlock.security.test.ts.
const PURIFY_CONFIG = {
ALLOWED_TAGS: [
'a','p','br','hr','div','span','section','article',
'header','footer','main','aside','nav',
'ul','ol','li',
'h1','h2','h3','h4','h5','h6','hgroup',
'em','strong','b','i','u','s',
'blockquote','code','pre',
'img','figure','figcaption',
'iframe',
// Tables: pasted content commonly includes these; dropping them
// silently ate customer-pasted tables (see C1 review finding).
'table','thead','tbody','tfoot','tr','td','th','caption','colgroup','col',
// Text semantics (Task 24).
'sub','sup','small','mark','del','ins','abbr','cite','q','time','data',
'kbd','samp','var','dfn','address','bdi','bdo','ruby','rt','rp','wbr',
// Lists (Task 24).
'dl','dt','dd','menu',
// Disclosure widget (Task 24). Note: <dialog> and <template> are
// deliberately NOT added -- the fixture exercises them wrapped in
// on*= handlers specifically to prove they still get neutralized/
// dropped by staying outside the allow-list.
'details','summary',
// Media (Task 24). URL-bearing attributes on these (poster, srcset,
// action, cite...) go through the ALLOWED_URI_REGEXP gate like
// everything else -- see _isValidAttribute in dompurify, which
// URI-checks every allowed attribute value except a small fixed
// "inert" list (alt, class, id, style, title, ...) that never includes
// src/poster/srcset. The one exception: `src` itself on img/video/
// audio/source/image/track is additionally covered by DOMPurify's own
// `DATA_URI_TAGS` allow-list, which accepts any data: URI on those
// tag/attribute pairs regardless of mimetype, bypassing this regex --
// see the ALLOWED_URI_REGEXP comment below and
// HtmlBlock.security.test.ts. Not a gap in the four non-negotiables:
// none of those tags execute their src as a document.
'picture','source','video','audio','track','canvas',
// Forms (Task 24). Site owner's explicit decision: allow the full
// ordinary form surface. No on*= survives (FORBID_ATTR below), and
// action/formaction-style URLs are gated by ALLOWED_URI_REGEXP the
// same as href/src, so `javascript:` still cannot survive here either.
'form','input','button','select','option','optgroup','textarea',
'label','fieldset','legend','datalist','output','progress','meter',
// Inline SVG (Task 24) -- see the block comment on IFRAME_SANDBOX_HOOK's
// neighbor below for why this is an explicit tag list rather than
// DOMPurify's USE_PROFILES svg profile. Deliberately excludes <use> and
// <image> (both need xlink:href, an external-reference vector DOMPurify
// itself excludes from its own SVG defaults) and <a>/<foreignObject>
// (not needed by the fixture; foreignObject can embed arbitrary HTML).
'svg','g','defs','symbol','title','desc','rect','circle','ellipse',
'line','polyline','polygon','path','text','tspan',
'lineargradient','radialgradient','stop','clippath','mask','marker',
'pattern','switch','view',
],
// NOTE: supplying ALLOWED_ATTR replaces DOMPurify's own default attribute
// allowlist rather than extending it, so anything the product needs
// (style, id, ...) must be listed explicitly here even though DOMPurify
// would allow it by default.
ALLOWED_ATTR: [
'href','src','alt','title','target','rel',
'width','height','class','id','style',
'allowfullscreen','allow','frameborder',
'sandbox','referrerpolicy',
// Task 24 additions.
'colspan','rowspan','scope','headers','span','start','reversed',
'type','value','name','placeholder','required','disabled','readonly',
'checked','selected','multiple','min','max','step','minlength',
'maxlength','pattern','rows','cols','accept','action','method','for',
'list','label','datetime','cite','lang','dir','role','srcset','media',
'sizes','loading','controls','poster','loop','muted','autoplay',
'preload','playsinline','kind','srclang','default','open','download',
'hidden','contenteditable',
// SVG presentation attributes (explicit route -- see ALLOWED_TAGS
// comment on the SVG tag list). Covers the fixture's <svg viewBox
// role>/<rect>/<circle>/<text> block plus the common presentation
// attributes for the shapes/gradients allowed above. Deliberately
// excludes xlink:href (no <use>/<image> allowed, so it has nothing
// legitimate to attach to) and the SMIL/animation attributes (begin,
// dur, repeatCount, ...) which DOMPurify's own SVG defaults exclude
// for the same reason on* handlers are excluded.
'viewbox','cx','cy','r','rx','ry','x','y','x1','y1','x2','y2',
'points','d','fill','stroke','stroke-width','stroke-linecap',
'stroke-linejoin','stroke-dasharray','fill-rule','clip-rule','opacity',
'fill-opacity','stroke-opacity','text-anchor','dominant-baseline',
'font-family','font-size','font-weight','transform','offset',
'stop-color','stop-opacity','gradientunits','gradienttransform',
'preserveaspectratio',
],
// Review fix (Task 24 follow-up): the data:image arm used to sit inside
// the group that gets a trailing `:` appended for every alternative
// (`(?:https?|mailto|tel|data:image\/[a-z]+;base64,):`), so it required
// a SECOND colon after the one already in "base64,figure" -- no real
// data URI has that, so the clause could never match. It is now its own
// top-level alternative. NOTE: this regex is not the only thing gating
// data: URIs -- DOMPurify has its own internal `DATA_URI_TAGS` allow-list
// (img/video/audio/source/image/track) that accepts ANY data: URI on
// those tag/attribute pairs regardless of declared mimetype, bypassing
// this regex entirely. See HtmlBlock.security.test.ts for a regression
// test documenting that (acceptable: none of those tags execute their
// src as a document in mainstream browsers, and <iframe> -- which would
// be dangerous -- is correctly not in that DOMPurify list).
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel):|data:image\/[a-z]+;base64,|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
// form/input/button/select/textarea removed from FORBID_TAGS (Task 24) --
// they are now deliberately allowed above. style/script/object/embed/
// link/meta stay forbidden; <style> in particular stays blocked even
// inside the newly-allowed inline <svg> (a separate task is adding
// scoped <style> support later -- see HtmlBlock.security.test.ts for the
// svg><style> regression check).
FORBID_TAGS: ['script','style','object','embed','link','meta'],
FORBID_ATTR: [/^on/i],
};
// M-6: `<iframe>` is allowed (maps/video embeds are a legitimate use case)
// but an iframe with a `src` and NO `sandbox` attribute is a clickjacking/
// phishing vector (DOMPurify already strips <script>/on*=, but an
// unsandboxed iframe still gets full script execution, same-origin-ish
// access via document.domain tricks, top-level navigation, etc., inside
// itself). This hook force-sets a restrictive sandbox on every iframe that
// survives sanitization, keeping `allow-scripts`/`allow-same-origin`/
// `allow-popups`/`allow-forms` (needed for interactive maps/video/oauth
// popups) but deliberately omitting `allow-top-navigation` so an embedded
// page can never redirect/hijack the parent tab.
const IFRAME_SANDBOX_HOOK = (node: Element): void => {
if (node.nodeName === 'IFRAME') {
node.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups allow-forms');
node.setAttribute('referrerpolicy', 'no-referrer');
}
};
export function purifyHtml(input: string): string {
// Hook is added immediately before sanitize() and removed immediately
// after, scoped tightly to this single call -- so it can never leak onto
// (or accumulate duplicate copies across) any other DOMPurify.sanitize()
// call elsewhere in the app, and repeated purifyHtml() calls never stack
// multiple copies of the same hook.
DOMPurify.addHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK);
try {
return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
} finally {
DOMPurify.removeHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK as any);
}
}
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '' }) => {
const { connectors: { connect, drag }, selected } = useNode((node) => ({ selected: node.events.selected }));
const clean = useMemo(() => purifyHtml(code), [code]);
const setRef = (ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); };
// The `style` prop is deliberately NOT applied. `toHtml()` emits only the
// purified `code`, so anything styled here would show in the editor and
// vanish on the live page -- the exact bug this block was reported for.
// Wrapper styling belongs in the user's own markup (see the Edit HTML
// toolbar's colour control). `style` stays on the props interface so
// already-saved sites keep deserializing cleanly.
return React.createElement('div', {
ref: setRef,
style: {
minHeight: '40px',
outline: selected ? '2px solid #3b82f6' : 'none',
},
dangerouslySetInnerHTML: { __html: clean },
});
};
/* ---------- Craft config ---------- */
HtmlBlock.craft = {
displayName: 'HTML',
props: {
code: '',
style: {},
},
rules: {
canDrag: () => true,
canMoveIn: () => false,
canMoveOut: () => true,
},
};
/* ---------- HTML export ---------- */
(HtmlBlock as any).toHtml = (props: HtmlBlockProps, _childrenHtml: string) => {
// Run through the same DOMPurify config used for the live editor preview
// so exported pages can't carry <script>/on*= payloads either.
return { html: purifyHtml(props.code || '') };
};