Markdown-syntax and raw-HTML file: destinations are converted to an absolute local path before rendering or sanitization, then served by the same session media route as relative images. POSIX, Windows drive, localhost, UNC and percent-encoded URLs are covered; the file: scheme is never handed to the renderer or DOMPurify. Also prepares v0.31.1.
483 lines
20 KiB
TypeScript
483 lines
20 KiB
TypeScript
/**
|
|
* MarkdownDocument spec: the split-document renderer — sanitized HTML leaves
|
|
* (denylist + anchor hardening + local media rewrite), `<details>` nesting of
|
|
* in-between markdown, cross-segment reference definitions, and the inline
|
|
* pass that turns tag text inside rendered markdown back into elements.
|
|
* Renders with the real shared MarkdownText in jsdom (same pattern as
|
|
* tests/mermaid-markdown.spec.tsx).
|
|
*/
|
|
// @vitest-environment jsdom
|
|
import { describe, expect, it, beforeEach } from 'vitest'
|
|
import { createElement } from 'react'
|
|
import { createRoot, type Root } from 'react-dom/client'
|
|
import { act } from 'react-dom/test-utils'
|
|
import { MarkdownDocument, type MarkdownHtmlMedia } from '../src/client/MarkdownHtml.tsx'
|
|
import { analyzeMarkdownHtml } from '../src/client/markdown-html.ts'
|
|
import { createMarkdownPathImages } from '../src/client/markdown-images.ts'
|
|
|
|
// The act() environment flag (React 18.2 reads it before flushing effects).
|
|
import { setupReactAct } from './test-utils.ts'
|
|
setupReactAct()
|
|
|
|
const media: MarkdownHtmlMedia = {
|
|
scope: { sessionId: 's1', cwd: '/ws' },
|
|
path: '/ws/docs/README.md',
|
|
baseUrl: 'http://gui.origin/proxy/3080/',
|
|
}
|
|
/** The desktop shell's page origin: the Host listens on a different site. */
|
|
const desktopMedia: MarkdownHtmlMedia = {
|
|
scope: { sessionId: 's1', cwd: '/ws' },
|
|
path: '/ws/docs/README.md',
|
|
baseUrl: 'dsh-app://app/',
|
|
}
|
|
const codeLabels = {
|
|
copyLabel: 'Copy', copiedLabel: 'Copied', codeLabel: 'Code block', wrapLabel: 'Wrap lines', unwrapLabel: 'Do not wrap lines',
|
|
}
|
|
|
|
/**
|
|
* Render one document with the Markdown owner's `pathImages` vocabulary — the
|
|
* production wiring: local markdown images resolve through the page-base
|
|
* vocabulary, which is also the only branch that renders from the desktop
|
|
* shell's `dsh-app://` page (regression covered below).
|
|
*/
|
|
async function renderDocument(
|
|
text: string,
|
|
renderMedia: MarkdownHtmlMedia = media,
|
|
): Promise<{ container: HTMLElement; root: Root }> {
|
|
const container = document.createElement('div')
|
|
document.body.appendChild(container)
|
|
const root = createRoot(container)
|
|
const mediaWithImages: MarkdownHtmlMedia = {
|
|
...renderMedia,
|
|
pathImages: renderMedia.pathImages
|
|
?? createMarkdownPathImages(renderMedia.scope, renderMedia.path, renderMedia.baseUrl),
|
|
}
|
|
await act(async () => {
|
|
root.render(createElement(MarkdownDocument, {
|
|
info: analyzeMarkdownHtml(text),
|
|
media: mediaWithImages,
|
|
codeLabels,
|
|
}))
|
|
// Let the MutationObserver's queued inline pass settle inside the act scope.
|
|
await new Promise((resolve) => { setTimeout(resolve, 0) })
|
|
})
|
|
return { container, root }
|
|
}
|
|
|
|
async function unmount(root: Root): Promise<void> {
|
|
await act(async () => { root.unmount() })
|
|
}
|
|
|
|
beforeEach(() => {
|
|
document.body.innerHTML = ''
|
|
})
|
|
|
|
describe('MarkdownDocument (HTML leaves)', () => {
|
|
it('renders a balanced HTML block as sanitized DOM, not literal text', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'# Title',
|
|
'',
|
|
'<div align="center">',
|
|
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
|
|
'</div>',
|
|
].join('\n'))
|
|
const leaf = container.querySelector('[data-dsh-html-segment]')
|
|
expect(leaf, 'the html run must render as a sanitized leaf').not.toBeNull()
|
|
expect(leaf?.querySelector('img[src*="img.shields.io"]')).not.toBeNull()
|
|
expect(leaf?.firstElementChild?.getAttribute('align')).toBe('center')
|
|
expect(container.textContent).not.toContain('<div')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('strips denied tags and hardens anchors', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<div>',
|
|
' <script>alert(1)</script>',
|
|
' <a href="https://example.com">link</a>',
|
|
'</div>',
|
|
].join('\n'))
|
|
expect(container.querySelector('script')).toBeNull()
|
|
const anchor = container.querySelector('a[href="https://example.com"]')
|
|
expect(anchor).not.toBeNull()
|
|
expect(anchor?.getAttribute('target')).toBe('_blank')
|
|
expect(anchor?.getAttribute('rel')).toBe('noopener noreferrer')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('rewrites local media sources through the /sidebar/file route', async () => {
|
|
const { container, root } = await renderDocument('<picture><img src="./shot.png" alt="shot"/></picture>')
|
|
const img = container.querySelector('img')
|
|
expect(img?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('rewrites a raw HTML file: URL through /sidebar/file', async () => {
|
|
const { container, root } = await renderDocument('<img src="file:///ws/docs/shot.png" alt="shot"/>')
|
|
const img = container.querySelector('img')
|
|
expect(img).not.toBeNull()
|
|
expect(img?.getAttribute('src')).toBe(
|
|
'http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws',
|
|
)
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps an inline data:image through DOMPurify', async () => {
|
|
const dataUrl = 'data:image/png;base64,iVBORw0KGgo='
|
|
const { container, root } = await renderDocument(`<img src="${dataUrl}" alt="pasted"/>`)
|
|
const img = container.querySelector('img')
|
|
expect(img, 'raw HTML data:image must survive the sanitizer as <img>').not.toBeNull()
|
|
expect(img?.getAttribute('src')).toBe(dataUrl)
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (nesting + markdown runs)', () => {
|
|
it('nests markdown runs inside an unclosed <details> element', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<details>',
|
|
'<summary><b>更新</b></summary>',
|
|
'',
|
|
'```sh',
|
|
'dsh plugin --profile web add x',
|
|
'```',
|
|
'',
|
|
'</details>',
|
|
'',
|
|
'after the fold',
|
|
].join('\n'))
|
|
const details = container.querySelector('details')
|
|
expect(details, 'the open part must lower following runs into a details element').not.toBeNull()
|
|
// Direct child, not just a descendant: HTML only treats a summary as the
|
|
// disclosure widget in that position (a nested one gets the UA's own
|
|
// "Details" label and the authored text drops into the body).
|
|
const summary = details?.querySelector(':scope > summary')
|
|
expect(summary, 'the summary must be a direct child of <details>').not.toBeNull()
|
|
expect(summary?.textContent).toBe('更新')
|
|
expect(summary?.querySelector('b'), 'inline markup inside the summary must survive').not.toBeNull()
|
|
expect(details?.textContent).toContain('dsh plugin --profile web add x')
|
|
// The close part pops the frame: the trailing markdown is a sibling.
|
|
expect(details?.textContent).not.toContain('after the fold')
|
|
expect(container.querySelector('details')?.nextElementSibling?.textContent).toContain('after the fold')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps the authored summary label and the markdown run inside <details>', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<details>',
|
|
'<summary>Implementation internals — click to expand</summary>',
|
|
'',
|
|
'The bundle is a static patch document.',
|
|
'',
|
|
'</details>',
|
|
'',
|
|
'outside the fold',
|
|
].join('\n'))
|
|
const details = container.querySelector('details')
|
|
const summary = details?.querySelector(':scope > summary')
|
|
expect(summary?.textContent).toBe('Implementation internals — click to expand')
|
|
// The leaf wrapper must not sit between the details and its summary.
|
|
expect(details?.firstElementChild?.tagName).toBe('SUMMARY')
|
|
expect(details?.querySelector('[data-dsh-html-segment]'), 'no leaf wrapper around the summary').toBeNull()
|
|
const paragraph = [...(details?.querySelectorAll('p') ?? [])]
|
|
.find((node) => node.textContent?.includes('The bundle is a static patch document.'))
|
|
expect(paragraph, 'the following markdown run must stay inside the details').not.toBeUndefined()
|
|
expect(details?.textContent).not.toContain('outside the fold')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('never injects a hardcoded disclosure label', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<details>',
|
|
'<summary>Folded details</summary>',
|
|
'',
|
|
'body',
|
|
'',
|
|
'</details>',
|
|
].join('\n'))
|
|
expect(container.textContent).not.toContain('Details')
|
|
expect(container.textContent).not.toContain('详情')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps a summary leaf inside a non-details wrapper', async () => {
|
|
// The hoist is details-specific: a balanced run that merely starts with a
|
|
// summary (no <details> frame open) must still take the plain leaf path.
|
|
const { container, root } = await renderDocument([
|
|
'<div>',
|
|
'<summary>not a disclosure widget here</summary>',
|
|
'</div>',
|
|
].join('\n'))
|
|
const leaf = container.querySelector('[data-dsh-html-segment]')
|
|
expect(leaf, 'the run must stay a sanitized leaf').not.toBeNull()
|
|
expect(leaf?.querySelector('summary')).not.toBeNull()
|
|
expect(container.querySelector('details')).toBeNull()
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps trailing leaf content after a hoisted summary', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<details><summary>label</summary>',
|
|
'trailing html line',
|
|
].join('\n'))
|
|
const details = container.querySelector('details')
|
|
expect(details?.querySelector(':scope > summary')?.textContent).toBe('label')
|
|
expect(details?.textContent).toContain('trailing html line')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps reference definitions resolving across lifted HTML runs', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'see [the docs][shared]',
|
|
'',
|
|
'<div align="center">badges</div>',
|
|
'',
|
|
'[shared]: https://example.com/docs',
|
|
].join('\n'))
|
|
const anchor = container.querySelector('a[href="https://example.com/docs"]')
|
|
expect(anchor, 'a definition after an HTML run must still resolve').not.toBeNull()
|
|
expect(anchor?.textContent).toContain('the docs')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('renders a forbidden wrapper as transparent (children survive)', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<form action="/x">',
|
|
'',
|
|
'inner text',
|
|
'',
|
|
'</form>',
|
|
].join('\n'))
|
|
expect(container.querySelector('form')).toBeNull()
|
|
expect(container.textContent).toContain('inner text')
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (inline pass)', () => {
|
|
it('turns tag text in table cells back into elements', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'| feature | notes |',
|
|
'|---|---|',
|
|
'| alpha | line one<br/>line two |',
|
|
].join('\n'))
|
|
const cell = [...container.querySelectorAll('td')].find((td) => td.textContent?.includes('line one'))
|
|
expect(cell?.querySelector('[data-html-inline] br'), 'the <br/> must render as a real element').not.toBeNull()
|
|
await unmount(root)
|
|
})
|
|
|
|
it('leaves rendered code and comparison prose untouched', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'a < b comparison stays text',
|
|
'',
|
|
'```html',
|
|
'<div>demo</div>',
|
|
'```',
|
|
].join('\n'))
|
|
expect(container.querySelectorAll('[data-html-inline]').length).toBe(0)
|
|
expect(container.textContent).toContain('a < b comparison stays text')
|
|
const code = container.querySelector('code')
|
|
expect(code?.textContent).toContain('<div>demo</div>')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('rewrites local image src inside inline-swapped tags', async () => {
|
|
const { container, root } = await renderDocument('text <img src="./icon.png" alt="i"/> tail')
|
|
const img = container.querySelector('[data-html-inline] img')
|
|
expect(img?.getAttribute('src')).toContain('/sidebar/file?')
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (isolated close tags)', () => {
|
|
// The host renderer emits one text node per raw-HTML token, so a README's
|
|
// `<a id="x"></a>` arrives as two siblings: the open tag (sanitized into a
|
|
// real element) and a lone `</a>` that DOMPurify can only drop. That stray
|
|
// node used to fall through the "keep prose untouched" branch and print the
|
|
// source's `</a>` into the preview.
|
|
it('drops a stray close tag instead of printing it, keeping the anchor id', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<a id="understand-the-implementation"></a>',
|
|
'',
|
|
'## Heading',
|
|
].join('\n'))
|
|
expect(container.textContent, 'the raw close tag must not reach the page').not.toContain('</a>')
|
|
const anchor = container.querySelector('a#understand-the-implementation')
|
|
expect(anchor, 'the anchor id must survive (deep links target it)').not.toBeNull()
|
|
expect(anchor?.textContent).toBe('')
|
|
expect(container.textContent).toContain('Heading')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('drops isolated inline-only close tags that stay in the markdown run', async () => {
|
|
// Block-level close lines (`</div>`) are lifted into their own HTML run and
|
|
// never reach this pass; the tags below are inline-only, stay in the
|
|
// markdown run, and are the ones the pass has to drop.
|
|
const { container, root } = await renderDocument([
|
|
'before the run',
|
|
'',
|
|
'</a>',
|
|
'',
|
|
'between',
|
|
'',
|
|
'</sub>',
|
|
'',
|
|
'after the run',
|
|
].join('\n'))
|
|
expect(container.textContent).not.toContain('</a>')
|
|
expect(container.textContent).not.toContain('</sub>')
|
|
expect(container.textContent).toContain('before the run')
|
|
expect(container.textContent).toContain('between')
|
|
expect(container.textContent).toContain('after the run')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('never prints a stray block-level close line either', async () => {
|
|
// The block-run path (frame stack) already drops top-level stray closes —
|
|
// pinned here so the "no source close tag on screen" acceptance holds for
|
|
// block tags too, not just for the inline pass.
|
|
const { container, root } = await renderDocument([
|
|
'before',
|
|
'',
|
|
'</div>',
|
|
'',
|
|
'</p>',
|
|
'',
|
|
'after',
|
|
].join('\n'))
|
|
expect(container.textContent).not.toContain('</div>')
|
|
expect(container.textContent).not.toContain('</p>')
|
|
expect(container.textContent).toContain('before')
|
|
expect(container.textContent).toContain('after')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('leaves comparison prose untouched', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'a < b and x </ y and 1 < 2 all stay text',
|
|
].join('\n'))
|
|
expect(container.textContent).toContain('a < b and x </ y and 1 < 2 all stay text')
|
|
expect(container.querySelectorAll('[data-html-inline]').length).toBe(0)
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (local markdown images)', () => {
|
|
it('renders markdown-syntax local images through the /sidebar/file route', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'# Title',
|
|
'',
|
|
'',
|
|
'',
|
|
'![logo][logo]',
|
|
'',
|
|
'[logo]: ./logo.png',
|
|
].join('\n'))
|
|
const imgs = [...container.querySelectorAll('img')]
|
|
expect(imgs.length, 'both local images must render as <img>, not alt fallback').toBe(2)
|
|
expect(imgs[0]?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fassets%2Ficon.svg&cwd=%2Fws')
|
|
expect(imgs[0]?.getAttribute('alt')).toBe('icon')
|
|
expect(imgs[1]?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Flogo.png&cwd=%2Fws')
|
|
expect(imgs[1]?.getAttribute('alt')).toBe('logo')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('renders local markdown images in HTML-mixed documents (the production path)', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<div align="center">badges</div>',
|
|
'',
|
|
'',
|
|
].join('\n'))
|
|
const img = container.querySelector('img')
|
|
expect(img, 'the markdown-syntax image after an HTML run must render').not.toBeNull()
|
|
expect(img?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps remote image destinations untouched', async () => {
|
|
const { container, root } = await renderDocument('')
|
|
const img = container.querySelector('img')
|
|
expect(img?.getAttribute('src')).toBe('https://example.com/x.png')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('renders a markdown-syntax file: URL through the media routes', async () => {
|
|
for (const [renderMedia, expected] of [
|
|
[media, 'http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fpic.png&cwd=%2Fws'],
|
|
[desktopMedia, 'dsh-app://app/api/file?path=%2Fws%2Fdocs%2Fpic.png'],
|
|
] as const) {
|
|
const { container, root } = await renderDocument('', renderMedia)
|
|
const img = container.querySelector('img')
|
|
expect(img, 'a file: URL image must render as <img>, not alt').not.toBeNull()
|
|
expect(img?.getAttribute('src')).toContain(expected)
|
|
await unmount(root)
|
|
}
|
|
})
|
|
|
|
it('renders a markdown-syntax image data URI (the only data: the vocabulary admits)', async () => {
|
|
const dataUrl = 'data:image/png;base64,iVBORw0KGgo='
|
|
for (const renderMedia of [media, desktopMedia]) {
|
|
const { container, root } = await renderDocument(``, renderMedia)
|
|
const img = container.querySelector('img')
|
|
expect(img, 'a data:image destination must render as <img>, not alt').not.toBeNull()
|
|
expect(img?.getAttribute('src')).toBe(dataUrl)
|
|
expect(img?.getAttribute('alt')).toBe('pasted')
|
|
await unmount(root)
|
|
}
|
|
})
|
|
|
|
it('leaves a non-image data destination as alt text', async () => {
|
|
const { container, root } = await renderDocument('')
|
|
expect(container.querySelector('img')).toBeNull()
|
|
expect(container.textContent).toContain('x')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('is idempotent for already-rewritten media URLs', async () => {
|
|
const url = 'http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws'
|
|
const { container, root } = await renderDocument(``)
|
|
const img = container.querySelector('img')
|
|
expect(img?.getAttribute('src')).toBe(url)
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (desktop shell page origin)', () => {
|
|
// Regression: the desktop shell serves the GUI from `dsh-app://app/` and the
|
|
// Host listens on another origin (`__DSH_TRANSPORT__.streamBaseUrl`). A
|
|
// transport-origin http media URL is therefore a CROSS-SITE subresource, the
|
|
// Host's Connection fence rejects it (403) and MarkdownText falls back to the
|
|
// image's alt text — exactly the bug this suite pins. Markdown syntax is
|
|
// limited to the renderer's local-file vocabulary (`dsh-app://app/api/file`),
|
|
// whose request the shell forwards to the Host with the launch cookie.
|
|
it('renders markdown-syntax local images from the dsh-app page origin', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'',
|
|
'',
|
|
'![logo][logo]',
|
|
'',
|
|
'[logo]: ./logo.png',
|
|
].join('\n'), desktopMedia)
|
|
const imgs = [...container.querySelectorAll('img')]
|
|
expect(imgs.length, 'both local images must render as <img>, not alt fallback').toBe(2)
|
|
// The host appends its own freshness counter to /api/file URLs; the path is
|
|
// the contract, the counter is render-time bookkeeping.
|
|
for (const [img, expected] of [
|
|
[imgs[0], 'dsh-app://app/api/file?path=%2Fws%2Fdocs%2Fassets%2Ficon.svg'],
|
|
[imgs[1], 'dsh-app://app/api/file?path=%2Fws%2Fdocs%2Flogo.png'],
|
|
] as const) {
|
|
expect(img?.getAttribute('src')).toMatch(new RegExp(`^${expected.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}&load=\\d+$`))
|
|
}
|
|
await unmount(root)
|
|
})
|
|
|
|
it('renders raw-HTML local images from the dsh-app page origin', async () => {
|
|
const { container, root } = await renderDocument(
|
|
'<picture><img src="./shot.png" alt="shot"/></picture>',
|
|
desktopMedia,
|
|
)
|
|
const img = container.querySelector('img')
|
|
expect(img?.getAttribute('src')).toBe('dsh-app://app/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws')
|
|
await unmount(root)
|
|
})
|
|
})
|