Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(frontend): tolerate malformed EPUB paths and clean up failed previews (#4324)
Jarvis35fa71361719
diff --git a/frontend/src/utils/epubPreview.test.ts b/frontend/src/utils/epubPreview.test.tsindex 1a164201e..6a0c75834 100644--- a/frontend/src/utils/epubPreview.test.ts+++ b/frontend/src/utils/epubPreview.test.ts@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'import { after, test } from 'node:test'import JSZip from 'jszip'import { DOMParser as XmlParser, XMLSerializer } from '@xmldom/xmldom'-import { renderEpubPreview } from './epubPreview'+import { renderEpubPreview, resolveEpubPath } from './epubPreview'// Adapt the XML test DOM's missing browser conveniences. EPUB parsing and ZIP// resolution still run through the production renderer, with no mocked output.@@ -35,12 +35,15 @@ after(() => {const inlineImage = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='-async function fixture(body: string) {+async function fixture(body: string, imagePaths: string[] = []) {const zip = new JSZip()zip.file('META-INF/container.xml', '<container><rootfiles><rootfile full-path="EPUB/book.opf"/></rootfiles></container>')zip.file('EPUB/book.opf', '<package><manifest><item id="chapter" href="text/chapter.xhtml"/></manifest><spine><itemref idref="chapter"/></spine></package>')zip.file('EPUB/text/chapter.xhtml', `<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink"><head><title>Images</title></head><body>${body}</body></html>`)zip.file('EPUB/images/picture.gif', Buffer.from(inlineImage.split(',')[1], 'base64'))+ for (const path of imagePaths) {+ zip.file(path, Buffer.from(inlineImage.split(',')[1], 'base64'))+ }return zip.generateAsync({ type: 'arraybuffer' })}@@ -76,3 +79,73 @@ test('non-image data and executable image sources are not preserved', async () =assert.doesNotMatch(result.html, /data:text\/html|javascript:/)assert.deepEqual(result.objectUrls, [])})++test('EPUB resolves encoded paths and tolerates malformed percent escapes', () => {+ for (const [href, expected] of [+ ['../images/my%20picture.gif#cover', 'EPUB/images/my picture.gif'],+ ['../images/100%.gif', 'EPUB/images/100%.gif'],+ ['../images/bad%GG.gif', 'EPUB/images/bad%GG.gif'],+ ['../images/%E0%A4.gif', 'EPUB/images/%E0%A4.gif'],+ ]) {+ assert.equal(resolveEpubPath('EPUB/text/chapter.xhtml', href!), expected)+ }+})++test('malformed missing image paths do not hide the chapter or its working images', async () => {+ const result = await renderEpubPreview(await fixture(+ '<p>Readable chapter</p><img src="../images/picture.gif"/><img src="missing%.gif"/>' ++ '<svg xmlns="http://www.w3.org/2000/svg"><image href="missing%GG.gif"/><image xlink:href="missing%E0%A4.gif"/></svg>',+ ))+ try {+ assert.match(result.html, /Readable chapter/)+ assert.match(result.html, /data-epub-section="1"/)+ assert.equal(result.objectUrls.length, 1)+ assert.ok(result.html.includes(result.objectUrls[0]!))+ assert.doesNotMatch(result.html, /missing%/)+ assert.match(result.html, /src=""/)+ assert.equal((result.html.match(/href=""/g) || []).length, 2)+ } finally {+ result.objectUrls.forEach(url => URL.revokeObjectURL(url))+ }+})++test('EPUB reads literal percent filenames and normally encoded filenames from the ZIP', async () => {+ const result = await renderEpubPreview(await fixture(+ '<img src="../images/100%.gif"/><img src="../images/my%20picture.gif"/>',+ ['EPUB/images/100%.gif', 'EPUB/images/my picture.gif'],+ ))+ try {+ assert.equal(result.objectUrls.length, 2)+ for (const url of result.objectUrls) {+ assert.ok(result.html.includes(url))+ assert.deepEqual(Buffer.from(await (await fetch(url)).arrayBuffer()), Buffer.from(inlineImage.split(',')[1], 'base64'))+ }+ } finally {+ result.objectUrls.forEach(url => URL.revokeObjectURL(url))+ }+})++test('EPUB revokes previously created image URLs if rendering later fails', async (t) => {+ const createObjectURL = URL.createObjectURL.bind(URL)+ const revokeObjectURL = URL.revokeObjectURL.bind(URL)+ const created: string[] = []+ const failure = new Error('image URL allocation failed')+ t.mock.method(URL, 'createObjectURL', (blob: Blob) => {+ if (created.length === 2) throw failure+ const url = createObjectURL(blob)+ created.push(url)+ return url+ })+ const revoke = t.mock.method(URL, 'revokeObjectURL', revokeObjectURL)+ try {+ await assert.rejects(renderEpubPreview(await fixture(+ '<img src="../images/picture.gif"/><img src="../images/second.gif"/><img src="../images/third.gif"/>',+ ['EPUB/images/second.gif', 'EPUB/images/third.gif'],+ )), error => error === failure)+ assert.equal(created.length, 2)+ assert.deepEqual(revoke.mock.calls.map(call => call.arguments[0]), created)+ for (const url of created) await assert.rejects(fetch(url))+ } finally {+ created.forEach(revokeObjectURL)+ }+})diff --git a/frontend/src/utils/epubPreview.ts b/frontend/src/utils/epubPreview.tsindex 9d2c0b83d..ea079a87c 100644--- a/frontend/src/utils/epubPreview.ts+++ b/frontend/src/utils/epubPreview.ts@@ -24,7 +24,13 @@ const IMAGE_MIME: Record<string, string> = {/** Resolve `href` against the directory of `base` inside the archive. */export function resolveEpubPath(base: string, href: string): string {- const clean = decodeURIComponent(href.split('#')[0].split('?')[0])+ let clean = href.split('#')[0]!.split('?')[0]!+ try {+ clean = decodeURIComponent(clean)+ } catch {+ // Some archives contain literal percent signs or malformed escapes.+ // Try the original ZIP path rather than aborting the entire preview.+ }if (clean.startsWith('/')) return clean.slice(1)const parts = base.split('/').slice(0, -1)for (const seg of clean.split('/')) {@@ -89,32 +95,38 @@ export async function renderEpubPreview(data: ArrayBuffer): Promise<EpubPreview>return imageUrl(resolveEpubPath(chapter, source))}- const sections: string[] = []- for (let i = 0; i < spine.length; i++) {- const path = spine[i]- if (!path) continue- const text = await zip.file(path)?.async('string')- if (!text) continue- const doc = parseChapter(text)- const body = doc.body || doc.documentElement- for (const img of Array.from(body.querySelectorAll('img'))) {- const src = img.getAttribute('src')- img.setAttribute('src', src ? await resolveImageUrl(path, src) : '')- }- for (const image of byLocalName(body as Element, 'image')) {- const href = image.getAttribute('href') || image.getAttribute('xlink:href')- if (href) {- const url = await resolveImageUrl(path, href)- image.setAttribute('href', url)- image.removeAttribute('xlink:href')+ try {+ const sections: string[] = []+ for (let i = 0; i < spine.length; i++) {+ const path = spine[i]+ if (!path) continue+ const text = await zip.file(path)?.async('string')+ if (!text) continue+ const doc = parseChapter(text)+ const body = doc.body || doc.documentElement+ for (const img of Array.from(body.querySelectorAll('img'))) {+ const src = img.getAttribute('src')+ img.setAttribute('src', src ? await resolveImageUrl(path, src) : '')}+ for (const image of byLocalName(body as Element, 'image')) {+ const href = image.getAttribute('href') || image.getAttribute('xlink:href')+ if (href) {+ const url = await resolveImageUrl(path, href)+ image.setAttribute('href', url)+ image.removeAttribute('xlink:href')+ }+ }+ // Chapter links point inside the archive; keep the text, drop the target.+ for (const a of Array.from(body.querySelectorAll('a[href]'))) {+ const href = a.getAttribute('href') || ''+ if (!/^https?:/i.test(href)) a.removeAttribute('href')+ }+ sections.push(`<section class="epub-section" data-epub-section="${i + 1}">${body.innerHTML}</section>`)}- // Chapter links point inside the archive; keep the text, drop the target.- for (const a of Array.from(body.querySelectorAll('a[href]'))) {- const href = a.getAttribute('href') || ''- if (!/^https?:/i.test(href)) a.removeAttribute('href')- }- sections.push(`<section class="epub-section" data-epub-section="${i + 1}">${body.innerHTML}</section>`)+ return { html: sections.join('\n'), objectUrls }+ } catch (error) {+ // On success the caller owns these URLs; on failure it never receives them.+ objectUrls.forEach(url => URL.revokeObjectURL(url))+ throw error}- return { html: sections.join('\n'), objectUrls }}