Repository navigation
fix(core): keep parsed HTML out of the active document - #3393
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
@blocknote/ariakit
@blocknote/code-block
@blocknote/core
@blocknote/diagram-block
@blocknote/mantine
@blocknote/math-block
@blocknote/react
@blocknote/server-util
@blocknote/shadcn
@blocknote/xl-ai
@blocknote/xl-docx-exporter
@blocknote/xl-email-exporter
@blocknote/xl-multi-column
@blocknote/xl-odt-exporter
@blocknote/xl-pdf-exporter
@blocknote/xl-typst-exporter
commit: |
|
nperez0111
left a comment
There was a problem hiding this comment.
I like enforcing all the callsites, let's go one step further into a lint rule
| * HTML or markdown string, the HTML of an export). It has no browsing context: | ||
| * content in it cannot load a resource or run an event handler. | ||
| * | ||
| * Do all DOM work on such content in this document, never in the global |
There was a problem hiding this comment.
let's do a lint rule for this stuff
| // | Where | Not allowed | | ||
| // | ---------------------------------------- | ----------------------------------- | | ||
| // | 1. each file | `.cloneNode`, `.createHTMLDocument` | | ||
| // | 2. a file that only handles such content | global `document`, `.ownerDocument` | |
There was a problem hiding this comment.
@nperez0111 this is a bit tricky. We can have a lint rule that prvents rule 1 on every file. But we can't block all access to document or ownerDocument, because in some cases (e.g.: render() or toExternalHTML this is valid). We only want to prevent it on code that parses outside content.
Rules 2 and 3 try to prevent that (by blocking document for specific files and for any file inside a parse* function; but maybe we should drop rule 2 and 3 altogether as we already know it can't be 100% accurate (it would miss other filenames or function names). wdyt?
There was a problem hiding this comment.
I think we've been bitten by the whole accessing document thing a couple of times (relative to shadow-dom & iframe usage), so I actually would not be opposed to a blanket rule against touching document & then suppressing the rule on the line for the things we know that need them. This would sort of encourage us to be more intentional about when to use document & give a little friction which would be good to second guess it's usage if we can do it another way.
So maybe just apply the rule everywhere & suppress where needed
There was a problem hiding this comment.
check. even if it's like 30 places?
There was a problem hiding this comment.
render & toExternalHTML & parse can be rewritten (which I think is actually more valid). For example:
render (block, editor) {
document.createElement('h1')
// vs.
editor.domElement.ownerDocument.createElement('h1')
}
// we should make that less verbose
parse (el) {
el.querySelector()
el.ownerDocument.createElement()
}I think it is more accurate since it will always be in the correct "realm" if done like this since they will be relative to their inputs rather than having to pull in globals. But maybe this is too pedantic? I'll leave it to you. I would prefer if we could remove certain classes of errors (since it can be hard to know when it is important for shadow-dom or not, and we don't really have that many tests for shadow-dom).
There was a problem hiding this comment.
Not sure your exact example holds up (for example editor.domElement doesn't exist in headless editors), so it would require more investigation. I agree it would be great to better standardize how we access document safely. Atm though I think it'd be at least a day of work to come up with a good pattern and fix 135 spots (my 30 places earlier was too low).
I'd propose to get this PR in as it fixes some current potential security issues. I would drop lint rule 2 and 3 for now and create an engineering task to investigate all uses of document
There was a problem hiding this comment.
alright sure, fine with deferring
31f2407 to
ac056a2
Compare
ac056a2 to
c90a385
Compare
The fault: the HTML parse lost the `start` of a numbered list (for example `<ol start="2">`) if the first item of the list had a nested list. The markdown parse uses the HTML parse, so `3. a` with a nested list also became a list that starts at 1. The cause: before the parse rules run, the parser puts a list item with a nested list into a `div` element, together with the block group of the nested list (`createGroups` in `nestedLists.ts`). The parse rule of the numbered list item read the `start` attribute from the parent of the `<li>`. For such an item, the parent is that `div`, and not the list. The fix: for an item in a `div`, the rule reads `start` from the parent of the `div` (the list). It also uses the `div` to find out if the item is the first item of the list, so that a later item with a nested list does not get the start. The rule does not tell a `div` of the HTML source from the `div` of the parser. No known source writes `<ol><div><li>`.
The HTML parse moves a nested list out of its <li>, to make it a child block of the list item. It did not keep the other nodes of the <li> with the nested list: - Each node after the nested list went into a new item of the outer list. A paragraph became a new bullet. An image became an empty bullet with the image as its child. - When a block came between the content of the list item and the nested list (for example a code block), the nested list became a list after the list item, not a child of it. The markdown parse uses the HTML parse, thus it had the same fault. Now all the nodes after the own content of a list item move out of the <li> together, in order, into the block group of the list item. The parser makes the blocks from them. The own content is the text and the inline elements up to the first block, or else that first block if it is a paragraph, a heading, a code block or a quote with text. A comment, white space and an element without text are not content. If the first block is a different element (for example an image), the nodes before the nested list stay in the <li>, as before. Text directly after a nested list becomes a paragraph. It keeps one space at its start if the HTML has white space there, as each text after a block does in the parse (for example `<li><p>a</p> b</li>`). A <li> that starts with a nested list has no content of its own. As before, the nested list goes to the list item before it. Test changes: - nestedLists.browser.test.ts.snap: in "content after nested list" and "content in between", the text is in the block group of the list item, not in a new <li>. The other 4 changed snapshots change only by white space: the white space after a nested list moves with it into the block group. - parse html/emptyNestedCheckListItem: the paragraph is a child of the list item, not a new bullet. - parse markdown/complex: "Paragraph" is a paragraph child of its list item, and the lists after it are children of the same list item. It was a new bullet that took these lists as its children. - nestedLists.browser.test.ts, "stays out of the active document": the image after the nested list is in the block group of the list item, not in a new <li>. The test still sees an element of the HTML that goes into the active document. New cases in the parse tests (parseTestInstances.ts): 7 for HTML and 1 for markdown. The new elements of the two steps are made in `detachedDoc()`.
No test failed when one of these rules of `nestedLists.ts` was removed. Each new parse case fails without its rule: - listItemEmptyParagraphBeforeContent: an empty paragraph is not the content of the list item (`hasContent` in `isTextBlock`). - listItemTextAndBlockBeforeNestedList: the text before the first block is the content of the list item. - listItemLinkedImageBeforeNestedList: an image is a block, also in a link (the last line of `BLOCK_ELEMENTS`, `querySelector` in `isBlock`). - listItemHeadingCodeQuoteBeforeNestedList: a heading, a code block and a quote are text blocks (`isTextBlock`). - listItemContentInDivBeforeNestedList: a first block that is not a text block stays in the list item (the last line of `childrenStart`). - nestedListInOwnListItem, nestedCheckListInOwnListItem: a list item that holds only a nested list (the `start === 0` branch). - nestedListInAndNextToListItem: a list next to a list item that has a block group of step 1 (the loop in `createGroups`). The inputs are forms of Tiptap, Notion, GitHub, Plate and Lexical, and of markdown renderers. Three cases fail on `main`: listItemTextAndBlockBeforeNestedList, listItemLinkedImageBeforeNestedList and listItemHeadingCodeQuoteBeforeNestedList. The other five have the same result on `main`. They are guards. There is no source change.
BlockNote has no inline images: an image is a block. The HTML parser dropped an image that was in a `<p>` or a `<blockquote>` together with text. The markdown parser makes HTML first, so `Text  more` also lost its image, in a paragraph, in a quote and in a list item. The cause: the content of these blocks is parsed as inline content only, and ProseMirror has no place for an image block there. Before ProseMirror parses the HTML, each paragraph and each quote that has an image now splits around the image: the text before, the image, the text after. The parts are copies of the element, so they keep its type, its alignment and its colors. A part without text is removed. In a list item, the image and the text after it become children of the list item, as for an image that is directly in an `<li>`. A link or a style that holds the image splits in the same way. The image does not keep the link.
The HTML parser and the markdown parser dropped an image that was in the text of a heading, for example `## Title ` or `<h1><img src="logo.png"> Project</h1>`. The cause is the same as for a paragraph: the content of a heading is parsed as inline content only, and an image is a block. A heading now splits around the image, as a paragraph and a quote do. The parts are headings of the same level. An image at the start or at the end of the heading gives the image and one heading. An image between two texts gives two headings: `## A  B` becomes the heading `A`, the image and the heading `B`.
The HTML parser and the markdown parser dropped an image that was in a table cell, for example `|  |`. The cause: the content of a cell is parsed as blocks, and then only the inline content of these blocks goes into the cell. An image block has no inline content, so it was dropped. A table cell cannot hold a block, so a cell cannot split around the image as a paragraph does. Thus, before ProseMirror parses the HTML, a link to the image replaces each image that is in a cell. The link text is the alt text of the image, or its URL. Three snapshots of the HTML parse change: their table cells have an image without alt text, which is now a link with the URL as its text.
The step that moves an image out of the text also changed HTML that
BlockNote wrote, and text was lost.
Custom inline content can render an image, for example a mention with
an avatar. The HTML export of the paragraph `hi {mention} there` then
has an `<img>` in the text. The step split the paragraph at this image.
For the full HTML, the parse then gave only `hi`: a block of the full
HTML has one content element, and the split made two.
An image is now not moved and not replaced by a link if it is in custom
inline content (an element with `data-inline-content-type`) or in a
block of the full HTML (an element with `data-content-type`). For such
an image the parse gives the same result as before this step.
…a link In a table cell, a link replaces an image. The link mark of the editor does not take each URL: it refuses `file:`, `data:`, `blob:` and `javascript:`. For such an image the cell got the URL as plain text. A table from Word with a picture in a cell showed the local path of the picture, and a `data:` URL gave thousands of characters. The link now replaces the image only if `isAllowedUri`, the check of the link mark, accepts the URL of the image. In each other case the image stays as it is, and the parse of the cell drops it, as before this branch. This also applies to an image without a URL.
…splits a block When a block splits around an image, the text before the image kept the space at its end, and the text after the image started with a space: `a <img> b` gave `a `, the image and ` b`. An image on its own line (`Some text`, a line break, the image, a line break, `More text`) gave parts that ended and started with a line break. A line break or white space directly next to the image has no meaning at the edge of a block. At each split, the `<br>` elements and the white space text directly before and after the image are now removed. `a <img> b` gives `a`, the image and `b`. Nine snapshots change: only the spaces next to the image are gone.
The step that moves an image out of the text put the parts of each block before the block. In jsdom, the time to put a node before another node grows with the number of nodes before it. A document with 20,000 paragraphs that each have an image took about 115 s in jsdom, which is the server path. `main` takes about 2 s. The nodes of an element that are complete now go to a document fragment, and they come back at the end. They are removed from the start of the element, which is fast in jsdom. A block that splits is thus always near the start of its parent. The nodes before the image also move from the start of their parent now. The results do not change. In jsdom, 2,000 paragraphs with an image each now take about 0.3 s (before: 0.55 s), and 20,000 take about 3 s.
A review found changes of the image step that no test saw. These cases make each of them fail a test: - Text with a style before the image: the nodes before the image keep their order. - A paragraph with an image and a video and no text: a part without text is removed, but its other content stays. - A heading with an image and a space in a `<span>`: a part with only white space is not a block. - The heading levels 3 to 6. An image in a header cell of a table is in the case `imageUrlsInTableCell` of an earlier commit. A new case has an image without a URL in a table cell. One more case shows a known fault: a nested list after an image in a list item moves out of its item. The cause is the list parse, which does this for each list item that has a block as a child. The snapshot records the result of this branch alone. It changes when the list parse is corrected.
The summary of a `<details>` element is the text of a toggle. A toggle cannot split, so an image cannot go out of the summary. But the step split a heading or a paragraph that was in the summary. The parse of the toggle then put the parts together again, and the image was dropped. Since the step removes the space next to the image, this joined two words: `<summary><h2>Step <img> one</h2></summary>` gave the toggle heading `Stepone`. A toggle heading with only an image became a toggle list item. The step now does not change a summary. An image in a summary gives the same result as before this branch: the image is dropped, and the text stays as it is.
The HTML parse first moved the nested lists out of their list items, and then moved the images out of the text. For a list item with an image in its paragraph and a nested list, for example `<li><p>Step one <img></p><ul>...</ul></li>` or the markdown `1. Step one ` with sub items, the list steps saw a list item with one paragraph. The image came out of the paragraph later, and the nested list was then not in the list item: its items went to the top level, and a numbered list started again. The image step now runs first. The list steps then see the image as a block of the list item, and the image, the text after it and the nested list are children of the list item, in this order. For this, `HTMLToBlocks` makes the element for the HTML in `detachedDoc()`, runs the image step, then the list steps on this element, then the white space step. `nestedListsToBlockNoteStructure` now takes this element, not the HTML string. `HTMLToBlocks` is its one caller; its tests make the element in the same way.
The caption of a figure is text: the parse of a figure takes the text of its `<figcaption>`. An image cannot go out of the caption. But the step split a paragraph that was in the caption and removed the space next to the image. This joined two words: `<figcaption><p>cap <img> more</p></figcaption>` gave the caption `capmore`. The step now does not change a `<figcaption>`, as it does not change the summary of a toggle. An image in a caption gives the same result as before this branch: the image is dropped, and the text stays as it is.
`HTMLToBlocks` now makes the element for the HTML string. The test fails if that element is made in the active document.
`HTMLToBlocks` ran the image step for every schema. A schema without the image block drops an image in the parse, but the step split the block around the image first: `<p>Before <img> after</p>` became two paragraphs. Before this branch it was one paragraph. The step now runs only if the schema has the `image` node. Without the image block, each result is as before this branch, also in a table cell (no link).
main has 91 new commits. Most core conflicts come from core fixes of this branch that went to main as separate pull requests, often in a changed form. For these files, the form of main is the reviewed one. Resolutions: - y/extensions/blockMatchNodes.ts and its browser test, y/utils.ts and its test: the files of main (#3380: blocks pair by ID only). - api/nodeConversions/blockToNode.ts: main (#3383). - api/parsers/html/util/nestedLists.ts and its snapshot: main (#3393, #3404). - blocks/File/block.ts, createLinkWithCaption.ts: main (#3401, #3387). - blocks/Image, Video, Audio: main (#3400). - CheckListItem/block.ts: main (#3388). NumberedListItem/block.ts: main (#3403). - api/exporters/markdown/htmlToMarkdown.ts and api/parsers/markdown/markdownToHtml.ts: main (#3385, #3392, #3394, #3391 and later commits). The parts of the branch that main does not have and that the lens needs come back in separate commits after this merge. - markdownExporter.ts, parseMarkdown.ts, ExportManager.ts, copyExtension.ts, SideMenu/dragging.ts merged without a conflict, but they used the API of the old markdown files of the branch (`escapes`, `target`): main. - serializeBlocksExternalHTML.ts merged without a conflict, but the merge had the toggle child order fix two times and did not compile: the form of main (#3388), with the white space placeholder of the branch. - exportParseEqualityTestInstances.ts: main (the toggle case of #3388). - vite.config.ts: main, with the lint rules of the lens. - tests/vite.config.browser.ts: main, with the lens files. - pnpm-lock.yaml: main, then `vp install`. main moved the shared test document to tests/src/fixtures/exporters (#3420). The lens test helper imports it from there, and the xl-ai build does not include the lens test helpers and benchmarks (a package build cannot read a file outside the package).
Summary
The HTML parser of
@blocknote/corereads HTML in a document without a browsing context. There, an element cannot load a resource or run an event handler. In four places, the code put content of that HTML into the active document of the page, where both can occur. Thus HTML from a paste, or given totryParseHTMLToBlocks,pasteHTMLorpasteMarkdown, could run script in the page of the editor.Each fix is one commit. The element that gets the content is now in a document without a browsing context.
getListItemContent).detailselement (getDetailsContent): toggle list items and toggle headings.nestedListsToBlockNoteStructure). This place only started an image request, in WebKit and Firefox.htmlToMarkdown). This place started a second request for each video and audio block on a copy, a block drag and a markdown export.The last two commits make the pattern one rule, and the result of a parse stays the same. All DOM work on content from outside is in
detachedDoc(), one shared document without a browsing context (an internal helper, with the rule in its JSDoc): the code parses a string there, makes more elements there, and copies a node that it gets withdetachedDoc().importNode. Thus a parse helper does not depend on the document of the node that its caller gives it.Testing
@blocknote/corein Chromium, Firefox and WebKit: 2,228 passed (main: 2,213). The browser integration tests (2,343) and the Node tests pass as onmain.Notes
detailselement stays as the HTML has it. Before, it became an absolute URL with the URL of the page. Six parse snapshots change for this reason.blocknote-dom/no-active-document, inscripts/lint/detached-doc.mjs) enforces the rule ofutil/detachedDoc.tsfor the source of@blocknote/core. It has three checks: nocloneNodeand nocreateHTMLDocumentin each file; no globaldocumentand noownerDocumentin the files that only handle content from outside (parsers, paste handlers, markdown export, parse helpers); and the same in each parse function, which is a function with a name that starts withparseor containsParse. Seven correct uses have an exception with its reason.vite.config.tsonly turns the rule on.Summary by CodeRabbit