Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix: harden imported document processing

nash_sudf37a5134572
diff --git a/src-tauri/src/commands/ebook.rs b/src-tauri/src/commands/ebook.rs
index 51c5668f..d733665f 100644
--- a/src-tauri/src/commands/ebook.rs
+++ b/src-tauri/src/commands/ebook.rs
@@ -16,6 +16,7 @@ const MAX_EBOOK_BYTES: u64 = 100 * 1024 * 1024;
const MAX_EPUB_ENTRIES: usize = 10_000;
const MAX_EPUB_EXPANDED_BYTES: u64 = 512 * 1024 * 1024;
const MAX_EPUB_COMPRESSION_RATIO: u64 = 200;
+const MAX_EPUB_CHAPTER_BYTES: usize = 16 * 1024 * 1024;
const MAX_EXTRACTED_TEXT_BYTES: usize = 32 * 1024 * 1024;
const MAX_CHAPTERS: usize = 10_000;
@@ -66,6 +67,13 @@ fn validate_epub_archive(path: &str) -> Result<(), String> {
entry.name()
));
}
+ if is_epub_text_entry(entry.name()) && entry.size() > MAX_EPUB_CHAPTER_BYTES as u64 {
+ return Err(format!(
+ "EPUB text entry '{}' exceeds the {} MB safety limit",
+ entry.name(),
+ MAX_EPUB_CHAPTER_BYTES / 1024 / 1024
+ ));
+ }
expanded = expanded.saturating_add(entry.size());
if expanded > MAX_EPUB_EXPANDED_BYTES {
return Err(format!(
@@ -87,6 +95,17 @@ fn validate_epub_archive(path: &str) -> Result<(), String> {
Ok(())
}
+fn is_epub_text_entry(name: &str) -> bool {
+ matches!(
+ Path::new(name)
+ .extension()
+ .and_then(|extension| extension.to_str())
+ .map(str::to_ascii_lowercase)
+ .as_deref(),
+ Some("html" | "htm" | "xhtml" | "xml")
+ )
+}
+
fn extract_epub(path: &str) -> Result<String, String> {
validate_epub_archive(path)?;
let mut document =
@@ -129,6 +148,13 @@ fn extract_epub(path: &str) -> Result<String, String> {
if !mime.contains("html") && !mime.contains("xml") {
continue;
}
+ if bytes.len() > MAX_EPUB_CHAPTER_BYTES {
+ return Err(format!(
+ "EPUB chapter {} exceeds the {} MB safety limit",
+ index + 1,
+ MAX_EPUB_CHAPTER_BYTES / 1024 / 1024
+ ));
+ }
let text = html_to_text(&bytes)?;
if text.trim().is_empty() {
continue;
@@ -347,4 +373,11 @@ mod tests {
assert_eq!(sanitized, "Book Title xxxxxxxx");
assert!(!sanitized.contains('\n'));
}
+
+ #[test]
+ fn identifies_epub_text_entries_case_insensitively() {
+ assert!(is_epub_text_entry("OEBPS/chapter.XHTML"));
+ assert!(is_epub_text_entry("META-INF/container.xml"));
+ assert!(!is_epub_text_entry("OEBPS/images/cover.png"));
+ }
}
diff --git a/src/lib/ingest-sanitize.test.ts b/src/lib/ingest-sanitize.test.ts
index 21af1814..57b80b4d 100644
--- a/src/lib/ingest-sanitize.test.ts
+++ b/src/lib/ingest-sanitize.test.ts
@@ -92,6 +92,13 @@ describe("sanitizeIngestedFileContent", () => {
)
})
+ it("repairs a wikilink list without corrupting CRLF frontmatter", () => {
+ const input = "---\r\ntype: entity\r\nrelated: [[a]], [[b]]\r\n---\r\n# Body\r\n"
+ expect(sanitizeIngestedFileContent(input)).toBe(
+ "---\r\ntype: entity\r\nrelated: [\"[[a]]\", \"[[b]]\"]\r\n---\r\n# Body\r\n",
+ )
+ })
+
it("doesn't touch a single `key: [[a]]` (not a list — leave the user's intent alone)", () => {
const input = `---\nrelated: [[a]]\n---\nbody`
// Single-element nested-array form is rare but legal YAML;
diff --git a/src/lib/ingest-sanitize.ts b/src/lib/ingest-sanitize.ts
index 85450cb8..03cd24e1 100644
--- a/src/lib/ingest-sanitize.ts
+++ b/src/lib/ingest-sanitize.ts
@@ -153,12 +153,12 @@ function addMissingOpeningFrontmatterFence(content: string): string {
* outside the frontmatter block are left untouched.
*/
function repairWikilinkListsInFrontmatter(content: string): string {
- const fmRe = /^---\s*\r?\n([\s\S]*?)\r?\n---\s*(\r?\n|$)/
+ const fmRe = /^(---[ \t]*(\r?\n))([\s\S]*?)(\r?\n---[ \t]*(?:\r?\n|$))/
const m = content.match(fmRe)
if (!m) return content
- const repairedPayload = m[1]
- .split("\n")
+ const repairedPayload = m[3]
+ .split(/\r?\n/)
.map((line) => {
const lm = line.match(
/^(\s*[A-Za-z_][\w-]*\s*:\s*)(\[\[[^\]]+\]\](?:\s*,\s*\[\[[^\]]+\]\])+)\s*$/,
@@ -172,13 +172,10 @@ function repairWikilinkListsInFrontmatter(content: string): string {
.join(", ")
return `${lm[1]}[${items}]`
})
- .join("\n")
-
- // Replace ONLY the payload between fences; preserve the original
- // fence lines and trailing newline shape.
- return (
- content.slice(0, m.index! + 4) + // up to and including "---\n"
- repairedPayload +
- content.slice(m.index! + 4 + m[1].length)
- )
+ .join(m[2])
+
+ // Rebuild from captured delimiters instead of assuming the opening fence is
+ // four bytes. Windows CRLF makes `---\r\n` five bytes, and hard-coded offsets
+ // corrupt both the opening fence and the payload boundary.
+ return m[1] + repairedPayload + m[4] + content.slice(m[0].length)
}
diff --git a/src/lib/mineru.test.ts b/src/lib/mineru.test.ts
index 86adfd49..35c94d74 100644
--- a/src/lib/mineru.test.ts
+++ b/src/lib/mineru.test.ts
@@ -442,6 +442,35 @@ describe("parseWithMineru", () => {
expect(form.get("return_images")).toBe("true")
})
+ it("uses the data URI MIME type when the MinerU filename extension disagrees", async () => {
+ mockHttpFetch
+ .mockResolvedValueOnce(jsonResponse({ task_id: "task-1" }, { status: 202 }))
+ .mockResolvedValueOnce(jsonResponse({ status: "completed" }))
+ .mockResolvedValueOnce(jsonResponse({
+ results: {
+ doc: {
+ md_content: "![Chart](images/chart.jpg)",
+ images: { "chart.jpg": `data:image/png;base64,${btoa("png bytes")}` },
+ },
+ },
+ }))
+
+ const result = await parseWithMineruResult({
+ enabled: true,
+ backend: "local",
+ token: "",
+ modelVersion: "vlm",
+ localBackend: "hybrid-engine",
+ }, "/tmp/doc.pdf", undefined, undefined, undefined, {
+ projectPath: "/project",
+ sourceSummarySlug: "doc",
+ })
+
+ expect(result.markdown).toBe("![Chart](media/doc/mineru/images/image-1.png)")
+ expect(result.savedImages[0]?.mimeType).toBe("image/png")
+ expect(result.savedImages[0]?.relPath).toBe("media/doc/mineru/images/image-1.png")
+ })
+
it("requires a model server URL for official HTTP-client backends", async () => {
await expect(parseWithMineru({
enabled: true,
diff --git a/src/lib/mineru.ts b/src/lib/mineru.ts
index 6086b481..9e9bd0ae 100644
--- a/src/lib/mineru.ts
+++ b/src/lib/mineru.ts
@@ -190,6 +190,19 @@ function mineruImageMimeType(path: string): string {
}
}
+function mineruExtensionForMimeType(mimeType: string): string | null {
+ switch (mimeType.trim().toLowerCase()) {
+ case "image/jpeg": return "jpg"
+ case "image/png": return "png"
+ case "image/gif": return "gif"
+ case "image/webp": return "webp"
+ case "image/bmp": return "bmp"
+ case "image/svg+xml": return "svg"
+ case "image/tiff": return "tiff"
+ default: return null
+ }
+}
+
function safeMineruAssetSegment(segment: string): string {
const decoded = (() => {
try {
@@ -740,7 +753,11 @@ async function parseWithLocalMineru(
if (!match) continue
const sourceName = getFileName(normalizeMineruZipPath(rawName))
if (!sourceName || !isMineruImagePath(sourceName)) continue
- const extension = sourceName.split(".").pop()?.toLowerCase()
+ // The data URI describes the bytes actually written. The server's
+ // filename is untrusted lookup metadata and may carry a mismatched
+ // extension, which would break previews and downstream MIME handling.
+ const mimeType = match[1].toLowerCase()
+ const extension = mineruExtensionForMimeType(mimeType)
if (!extension) continue
// Server-provided names are untrusted and may collide or contain a
// Windows reserved device name. Generate deterministic local names
@@ -751,7 +768,7 @@ async function parseWithLocalMineru(
await writeFileBase64(absPath, match[2])
savedImages.push({
index: savedImages.length,
- mimeType: match[1],
+ mimeType,
page: null,
width: 0,
height: 0,