Potential fix for code scanning alert no. 1821: DOM text reinterpreted as HTML #4944
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Potential fix for https://github.com/codeharborhub/codeharborhub.github.io/security/code-scanning/1821
General approach: For a live code editor where executing HTML/JS is desired, the right fix is not to escape the content (that would defeat the editor) but to execute it in a constrained environment. The main mitigation is to sandbox the iframe and, ideally, give it a separate origin (
srcdocor blob URL) so code inside cannot access the main page’s cookies, localStorage, or DOM. We should avoiddocument.writeon a same-origincontentDocumentand instead rely onsrcDocplus thesandboxattribute (and only the minimal necessary sandbox flags).Concrete best fix here without changing functionality:
const document = iframe.contentDocument,documentContentsas a string,document.open()/write()/close()documentContents,iframe.srcdoc(oriframeRef.current!.srcdocin TSX),sandboxattribute on the<iframe>element that allows scripts but isolates them: e.g.sandbox="allow-scripts"(optionallyallow-same-originif truly needed, but avoiding it is more secure).This keeps the visible behavior (user’s HTML/CSS/JS renders and runs) but isolates it inside a sandboxed iframe where it cannot reach out to the parent window or sensitive APIs tied to the origin.
Specific changes in
src/pages/LiveEditor/BasicEditor.tsx:useEffect, remove use ofiframe.contentDocumentanddocument.write, and instead setiframe.srcdoc = documentContents;.<iframe>JSX element, add asandboxattribute (string) such assandbox="allow-scripts"so the editor still runs JavaScript but is isolated.No new libraries are required; we only use standard DOM APIs and JSX attributes.
Suggested fixes powered by Copilot Autofix. Review carefully before merging.