AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: support SVG image uploads and previews
tianma-if3519fc9ec3ca
diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.tsindex e07c736e..9a07965b 100644--- a/apps/api/src/mcp-tools.ts+++ b/apps/api/src/mcp-tools.ts@@ -686,7 +686,7 @@ const MCP_TOOL_DEFINITIONS = [properties: {memoId: { type: "string" },filename: { type: "string" },- mimeType: { type: "string", enum: ["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"] },+ mimeType: { type: "string", enum: ["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/svg+xml"] },dataBase64: { type: "string" },alt: { type: "string" },},diff --git a/apps/api/src/resource-routes.test.mjs b/apps/api/src/resource-routes.test.mjsindex ea35099c..f59dcf94 100644--- a/apps/api/src/resource-routes.test.mjs+++ b/apps/api/src/resource-routes.test.mjs@@ -435,3 +435,23 @@ describe("resource route contracts", () => {expect(batches).toBe(0);});});+++test("SVG image and legacy attachment responses are sandboxed without changing original bytes", async () => {+ const svg = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>';+ for (const kind of ["image", "attachment"]) {+ const environment = createEnvironment();+ environment.storage.resources = {+ get: async () => ({ body: new Blob([svg]).stream(), writeHttpMetadata: () => {} }),+ };+ const response = await createApp(agentAuth, async () => ({+ ...resourceRow, kind, mime_type: "image/svg+xml", filename: "diagram.svg",+ byte_size: new TextEncoder().encode(svg).length, storage_config_id: null,+ })).request("/api/v1/resources/res_1/blob", {}, environment);+ expect(response.status).toBe(200);+ expect(response.headers.get("content-type")).toBe("image/svg+xml");+ expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox");+ expect(response.headers.get("content-disposition")).toStartWith(kind === "image" ? "inline;" : "attachment;");+ expect(await response.text()).toBe(svg);+ }+});diff --git a/apps/api/src/resource-routes.ts b/apps/api/src/resource-routes.tsindex ba92dcf0..24f59c0d 100644--- a/apps/api/src/resource-routes.ts+++ b/apps/api/src/resource-routes.ts@@ -1,4 +1,4 @@-import { isPdfAttachment, resolvePlayableMediaMimeType, ResourceUpdateSchema, type MemoDetail, type Resource } from "@edgeever/shared";+import { resolveResourceUploadMimeType, setSvgResourceSecurityHeaders, isPdfAttachment, resolvePlayableMediaMimeType, ResourceUpdateSchema, type MemoDetail, type Resource } from "@edgeever/shared";import { zValidator } from "@hono/zod-validator";import type { Hono } from "hono";import { auditStatement } from "./audit";@@ -166,7 +166,7 @@ export const registerResourceRoutes = (const input = {memoId,filename: file.name,- mimeType: file.type || "application/octet-stream",+ mimeType: resolveResourceUploadMimeType(file.name, file.type),bytes: new Uint8Array(await file.arrayBuffer()),actor: getAuditActor(context),};@@ -320,6 +320,7 @@ export const registerResourceRoutes = (: contentDispositionAttachment(resource.filename),);headers.set("X-Content-Type-Options", "nosniff");+ setSvgResourceSecurityHeaders(headers);return new Response(object.body, { headers, status: byteRange.kind === "range" ? 206 : 200 });});diff --git a/apps/api/src/resource-service.test.mjs b/apps/api/src/resource-service.test.mjsindex 474b451a..8bece0cf 100644--- a/apps/api/src/resource-service.test.mjs+++ b/apps/api/src/resource-service.test.mjs@@ -67,12 +67,14 @@ describe("resource service contracts", () => {test("infers normalized image extensions", () => {expect(inferImageExtension("photo.JPEG", "application/octet-stream")).toBe(".jpg");expect(inferImageExtension("photo", "image/avif")).toBe(".avif");+ expect(inferImageExtension("diagram.SVG", "image/svg+xml")).toBe(".svg");});test("enforces upload type and size boundaries", () => {expect(() => validateImageUpload("image/png", MAX_IMAGE_UPLOAD_BYTES)).not.toThrow();expect(() => validateAttachmentUpload(MAX_ATTACHMENT_UPLOAD_BYTES)).not.toThrow();- expect(() => validateImageUpload("image/svg+xml", 128)).toThrow();+ expect(() => validateImageUpload("image/svg+xml", 128)).not.toThrow();+ expect(() => validateImageUpload("text/html", 128)).toThrow();expect(() => validateAttachmentUpload(MAX_ATTACHMENT_UPLOAD_BYTES + 1)).toThrow();});diff --git a/apps/api/src/resource-service.ts b/apps/api/src/resource-service.tsindex fba956e3..265f95a9 100644--- a/apps/api/src/resource-service.ts+++ b/apps/api/src/resource-service.ts@@ -1,7 +1,8 @@-import type {- Resource,- ResourceListItem,- ResourceStorageSummary,+import {+ SUPPORTED_IMAGE_MIME_TYPES,+ type Resource,+ type ResourceListItem,+ type ResourceStorageSummary,} from "@edgeever/shared";import { auditStatement } from "./audit";import type { AppContext, AuditActor, Bindings } from "./api-context";@@ -15,13 +16,7 @@ import type { DatabaseAdapter } from "./storage-contract";export const MAX_IMAGE_UPLOAD_BYTES = 100 * 1024 * 1024;export const MAX_ATTACHMENT_UPLOAD_BYTES = 1024 * 1024 * 1024;-export const SUPPORTED_IMAGE_MIME_TYPES = new Set([- "image/png",- "image/jpeg",- "image/gif",- "image/webp",- "image/avif",-]);+export { SUPPORTED_IMAGE_MIME_TYPES } from "@edgeever/shared";export type ResourceRow = {id: string;@@ -101,7 +96,7 @@ export const validateImageUpload = (mimeType: string, size: number) => {if (!SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) {throw new AppError("unsupported_media_type",- "Only PNG, JPEG, GIF, WebP and AVIF images are supported.",+ "Only PNG, JPEG, GIF, WebP, AVIF and SVG images are supported.",415,);}@@ -134,7 +129,7 @@ export const normalizeFilename = (filename: string) => filename.slice(0, 160);export const inferImageExtension = (filename: string, mimeType: string) => {- const extension = /\.(png|jpe?g|gif|webp|avif)$/i.exec(filename)?.[0]?.toLowerCase();+ const extension = /\.(png|jpe?g|gif|webp|avif|svg)$/i.exec(filename)?.[0]?.toLowerCase();if (extension) return extension === ".jpeg" ? ".jpg" : extension;switch (mimeType) {@@ -143,6 +138,7 @@ export const inferImageExtension = (filename: string, mimeType: string) => {case "image/gif": return ".gif";case "image/webp": return ".webp";case "image/avif": return ".avif";+ case "image/svg+xml": return ".svg";default: return "";}};diff --git a/apps/api/src/resource-upload-integration.test.mjs b/apps/api/src/resource-upload-integration.test.mjsindex 24971d6a..548df489 100644--- a/apps/api/src/resource-upload-integration.test.mjs+++ b/apps/api/src/resource-upload-integration.test.mjs@@ -75,6 +75,31 @@ describe("resource upload integration", () => {.toEqual(Buffer.from(await smallImage.arrayBuffer()));}+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 60"><rect width="100" height="60" fill="#07130b"/></svg>';+ // Include file pickers that provide no type or a generic binary type.+ for (const type of ["image/svg+xml", "", "application/octet-stream"]) {+ const { resource } = await client.uploadMemoResource(memo.memo.id, new File([svg], "diagram.SVG", { type }));+ expect(resource).toMatchObject({ kind: "image", mimeType: "image/svg+xml", filename: "diagram.SVG" });+ const response = await fetchEdgeEverApp(new Request(`http://edgeever.test${resource.url}`), environment,+ { waitUntil: () => undefined, passThroughOnException: () => undefined });+ expect(response.headers.get("content-disposition")).toStartWith("inline;");+ expect(response.headers.get("content-security-policy")).toContain("sandbox");+ expect(await response.text()).toBe(svg);+ }+ const svgUpload = await requestJson(environment, `/api/v1/memos/${memo.memo.id}/resource-uploads`, {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ filename: "diagram.svg", mimeType: "application/octet-stream", byteSize: svg.length }),+ });+ await requestJson(environment, `/api/v1/resource-uploads/${svgUpload.upload.id}/parts/1`, {+ method: "PUT", headers: { "Content-Type": "application/octet-stream", "Content-Length": String(svg.length) }, body: svg,+ });+ const multipartSvg = await requestJson(environment, `/api/v1/resource-uploads/${svgUpload.upload.id}/complete`, {+ method: "POST", headers: { "Content-Type": "application/json" }, body: "{}",+ });+ expect(multipartSvg.resource).toMatchObject({ kind: "image", mimeType: "image/svg+xml", filename: "diagram.svg" });+ const svgRow = database.query("SELECT object_key FROM resources WHERE id = ?").get(multipartSvg.resource.id);+ expect(await readFile(join(resourcesDirectory, svgRow.object_key), "utf8")).toBe(svg);+const file = new Uint8Array(8 * 1024 * 1024 + 3);file.fill(7);file.set([1, 2, 3], file.byteLength - 3);diff --git a/apps/api/src/resource-upload-service.ts b/apps/api/src/resource-upload-service.tsindex 2df664f4..3797ba0d 100644--- a/apps/api/src/resource-upload-service.ts+++ b/apps/api/src/resource-upload-service.ts@@ -1,4 +1,5 @@import {+ resolveResourceUploadMimeType,JsonBackupResourceMetadataSchema,type JsonBackupResource,type Resource,@@ -108,6 +109,7 @@ export const initiateResourceUpload = async (input: { memoId: string; filename: string; mimeType: string; byteSize: number },) => {await cleanupExpiredResourceUploads(context);+ input = { ...input, mimeType: resolveResourceUploadMimeType(input.filename, input.mimeType) };const kind = SUPPORTED_IMAGE_MIME_TYPES.has(input.mimeType) ? "image" : "attachment";if (kind === "image") validateImageUpload(input.mimeType, input.byteSize);else validateAttachmentUpload(input.byteSize);diff --git a/apps/api/src/share-routes.test.mjs b/apps/api/src/share-routes.test.mjsindex cbf9e5ac..e42dcce2 100644--- a/apps/api/src/share-routes.test.mjs+++ b/apps/api/src/share-routes.test.mjs@@ -629,3 +629,24 @@ describe("one-step memo sharing", () => {sqlite.close();});});+++test("public SVG previews use the same sandbox and preserve the original", async () => {+ const { sqlite, environment } = createDatabaseEnvironment();+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 10"><script>alert(1)</script></svg>';+ sqlite.query(`INSERT INTO resources (id, memo_id, object_key, kind, mime_type, filename, byte_size)+ VALUES (?, ?, ?, 'image', 'image/svg+xml', 'diagram.svg', ?)`)+ .run("res_svg", "memo_source", "svg-key", svg.length);+ environment.storage.resources = { get: async () => ({+ body: new Blob([svg]).stream(), writeHttpMetadata: () => {},+ }) };+ const app = new Hono();+ registerPublicShareRoutes(app);+ const response = await app.request(`/api/public/shares/${sourceToken}/resources/res_svg/blob`, {}, environment);+ expect(response.status).toBe(200);+ expect(response.headers.get("content-type")).toBe("image/svg+xml");+ expect(response.headers.get("content-disposition")).toStartWith("inline;");+ expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox");+ expect(await response.text()).toBe(svg);+ sqlite.close();+});diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.tsindex 8dbc1007..0083f729 100644--- a/apps/api/src/share-routes.ts+++ b/apps/api/src/share-routes.ts@@ -1,4 +1,4 @@-import { accountNoteProseFromRow, collectMemoLinkIds, isPdfAttachment, MemoShareUpdateSchema, NoteBodyFontUpdateSchema, NoteProseUpdateSchema, parsePublishedNoteBodyFont, publicNoteProseFromAccount, PublicShareUnlockSchema, resolveMemoContentDoc, resolvePlayableMediaMimeType, sanitizeNoteProseCss, type AccountNoteProse, type ManagedMemoShare, type MemoShare, type NoteProseAccountRow, type PublicMemoShare, type TiptapDoc } from "@edgeever/shared";+import { setSvgResourceSecurityHeaders, accountNoteProseFromRow, collectMemoLinkIds, isPdfAttachment, MemoShareUpdateSchema, NoteBodyFontUpdateSchema, NoteProseUpdateSchema, parsePublishedNoteBodyFont, publicNoteProseFromAccount, PublicShareUnlockSchema, resolveMemoContentDoc, resolvePlayableMediaMimeType, sanitizeNoteProseCss, type AccountNoteProse, type ManagedMemoShare, type MemoShare, type NoteProseAccountRow, type PublicMemoShare, type TiptapDoc } from "@edgeever/shared";import { zValidator } from "@hono/zod-validator";import type { Hono } from "hono";import type { AppContext, AppEnv } from "./api-context";@@ -160,6 +160,7 @@ export const serveSharedResource = async (c: AppContext, resource: SharedResourcheaders.set("Content-Disposition", contentDisposition(resource.kind, resource.mime_type, resource.filename));headers.set("Cache-Control", "private, no-store");headers.set("X-Content-Type-Options", "nosniff");+ setSvgResourceSecurityHeaders(headers);headers.set("X-Robots-Tag", "noindex, nofollow, noarchive");return new Response(object.body, { headers, status: byteRange.kind === "range" ? 206 : 200 });};diff --git a/apps/api/src/table-form-routes.ts b/apps/api/src/table-form-routes.tsindex ae2a08b4..1070d3fd 100644--- a/apps/api/src/table-form-routes.ts+++ b/apps/api/src/table-form-routes.ts@@ -1,4 +1,5 @@import {+ resolveResourceUploadMimeType,parseTableDocument,PublicShareUnlockSchema,PublicTableFormSubmissionSchema,@@ -301,7 +302,7 @@ export const registerPublicTableFormRoutes = (app: Hono<AppEnv>) => {workspaceId: form.workspace_id,memoId: form.memo_id,filename: file.name,- mimeType: file.type || "application/octet-stream",+ mimeType: resolveResourceUploadMimeType(file.name, file.type),bytes: new Uint8Array(await file.arrayBuffer()),actor,metadata: { tableFormId: form.id, pending: 1 },diff --git a/apps/desktop/src/main/resource-url.mjs b/apps/desktop/src/main/resource-url.mjsindex 169230dd..b5d9de85 100644--- a/apps/desktop/src/main/resource-url.mjs+++ b/apps/desktop/src/main/resource-url.mjs@@ -3,7 +3,7 @@ export const isSafeResourceId = (value) =>const INLINE_RESOURCE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp",- "image/x-icon", "application/pdf", "audio/mpeg", "audio/mp4", "audio/ogg",+ "image/x-icon", "image/svg+xml", "application/pdf", "audio/mpeg", "audio/mp4", "audio/ogg","audio/wav", "audio/webm", "video/mp4", "video/webm", "video/ogg",]);@@ -14,7 +14,9 @@ export const resourceResponseHeaders = (contentType, disposition = null) => {"Cache-Control": "no-store","Content-Type": inline ? type : "application/octet-stream","X-Content-Type-Options": "nosniff",- "Content-Security-Policy": "default-src 'none'; sandbox",+ "Content-Security-Policy": type === "image/svg+xml"+ ? "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox"+ : "default-src 'none'; sandbox",});if (disposition || !inline) headers.set("Content-Disposition", disposition || "attachment");return headers;diff --git a/apps/desktop/src/main/security-boundaries.test.mjs b/apps/desktop/src/main/security-boundaries.test.mjsindex 74941f13..3b627f15 100644--- a/apps/desktop/src/main/security-boundaries.test.mjs+++ b/apps/desktop/src/main/security-boundaries.test.mjs@@ -98,8 +98,8 @@ test("stored ACP programs are revalidated before the runtime can execute them",expect(executed).toBe(false);});-test("resource responses never inline active documents, including MIME variants", () => {- for (const type of ["text/html", "Text/HTML; charset=utf-8", "image/svg+xml", "application/xhtml+xml", "text/plain", "application/octet-stream"]) {+test("resource responses never inline HTML documents, including MIME variants", () => {+ for (const type of ["text/html", "Text/HTML; charset=utf-8", "application/xhtml+xml", "text/plain", "application/octet-stream"]) {const headers = resourceResponseHeaders(type);expect(headers.get("content-type")).toBe("application/octet-stream");expect(headers.get("content-disposition")).toBe("attachment");@@ -143,3 +143,15 @@ test("custom ACP executables cannot be anchored in renderer-writable client storawait expect(validateTrustedAcpPath(filename, { excludedRoot: directory })).rejects.toThrow(/client data directory/);} finally { await rm(directory, { recursive: true, force: true }); }});+++test("SVG previews retain MIME and sandbox scripts and external resources", () => {+ for (const type of ["image/svg+xml", "IMAGE/SVG+XML; charset=utf-8"]) {+ const headers = resourceResponseHeaders(type);+ expect(headers.get("content-type")).toBe("image/svg+xml");+ expect(headers.get("content-disposition")).toBeNull();+ expect(headers.get("content-security-policy")).toBe("default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox");+ expect(headers.get("x-content-type-options")).toBe("nosniff");+ expect(resourceResponseHeaders(type, 'attachment; filename="original.svg"').get("content-disposition")).toContain("original.svg");+ }+});diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift b/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swiftindex d9185a9c..6e5e58a6 100644--- a/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift+++ b/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift@@ -1244,6 +1244,7 @@ struct MemoEditView: View {let succeeded = await viewModel.performUpload {NSLog("MemoEditView insertImageData: start bytes=%d name=%@", data.count, filename)let compress = env.preferences.useCompression+ && TipTapResourceLoader.sniffImageMime(data) != "image/svg+xml"let prepared = compress? ImageCompressor.compressIfNeeded(data) // Android parity: WebP @ 0.82, max edge 2560: Self.preparedUpload(from: data, preferredName: filename)@@ -1355,6 +1356,7 @@ struct MemoEditView: View {case "image/png": ext = "png"case "image/gif": ext = "gif"case "image/webp": ext = "webp"+ case "image/svg+xml": ext = "svg"default: ext = "jpg"}let base = (preferredName as NSString).deletingPathExtensiondiff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex e269688d..d71e4ff3 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -126,6 +126,7 @@ import {} from "@/lib/editor-reading-gutter";import { EDITOR_CONTENT_MAX_WIDTH, EDITOR_OUTLINE_WIDTH } from "@/lib/workspace-ui";import {+ resolveResourceUploadMimeType,countMemoCharacters,createEdgeEverDocumentExtensions,getFrontMatterSource,@@ -993,6 +994,8 @@ const RichEditorPane = ({}, [focusMobileInputTarget, isMobileViewport, memo?.id, mobileDefaultEditMemoId, onMobileDefaultEditConsumed, readOnly]);const uploadEditorResource = useCallback(async (targetMemoId: string, uploadFile: File, isImage: boolean) => {+ const mimeType = resolveResourceUploadMimeType(uploadFile.name, uploadFile.type);+ if (mimeType !== uploadFile.type) uploadFile = new File([uploadFile], uploadFile.name, { type: mimeType, lastModified: uploadFile.lastModified });if (isImage && shouldUploadWithPicGo()) {const instanceKey = editorInstanceMemoIdentityRef.current.instanceKey;const external = await uploadImageWithPicGo(uploadFile, {@@ -1087,7 +1090,7 @@ const RichEditorPane = ({const imageReadiness: Promise<void>[] = [];const results = await processFileUploadBatch(files, async (file) => {- const isImage = SUPPORTED_PASTE_IMAGE_TYPES.has(file.type);+ const isImage = SUPPORTED_PASTE_IMAGE_TYPES.has(resolveResourceUploadMimeType(file.name, file.type));const shouldCompress = isImage && imageCompressionEnabledRef.current;const placeholder = placeholderByFile.get(file);if (placeholder) updateImageUploadPlaceholder(editorRef.current, placeholder,@@ -1100,7 +1103,7 @@ const RichEditorPane = ({}, async (uploadFile, file) => {const targetMemoId = resolveTargetMemoId();if (!targetMemoId) throw new Error("The active note changed during attachment upload");- const isImage = SUPPORTED_PASTE_IMAGE_TYPES.has(file.type);+ const isImage = SUPPORTED_PASTE_IMAGE_TYPES.has(resolveResourceUploadMimeType(file.name, file.type));const placeholder = placeholderByFile.get(file);setImageUploadState("uploading");if (placeholder) updateImageUploadPlaceholder(editorRef.current, placeholder,@@ -1465,14 +1468,14 @@ const RichEditorPane = ({if (!targetMemoId || effectiveReadOnly) return "";setImageUploadState("uploading");const results = await processFileUploadBatch(files, async (file) => {- const shouldCompress = SUPPORTED_PASTE_IMAGE_TYPES.has(file.type) && imageCompressionEnabledRef.current;+ const shouldCompress = SUPPORTED_PASTE_IMAGE_TYPES.has(resolveResourceUploadMimeType(file.name, file.type)) && imageCompressionEnabledRef.current;if (!shouldCompress) return file;setImageUploadState("compressing");return (await compressImageForUpload(file)).file;}, async (uploadFile, file) => {if (memoRef.current?.id !== targetMemoId) throw new Error("The active note changed during upload");setImageUploadState("uploading");- return uploadEditorResource(targetMemoId, uploadFile, SUPPORTED_PASTE_IMAGE_TYPES.has(file.type));+ return uploadEditorResource(targetMemoId, uploadFile, SUPPORTED_PASTE_IMAGE_TYPES.has(resolveResourceUploadMimeType(file.name, file.type)));});if (results.some((result) => result.status === "fulfilled")) {void queryClient.invalidateQueries({ queryKey: ["resources"] });diff --git a/apps/web/src/components/editor/editor-pane-helpers.ts b/apps/web/src/components/editor/editor-pane-helpers.tsindex e4f8fdaf..f08c0dba 100644--- a/apps/web/src/components/editor/editor-pane-helpers.ts+++ b/apps/web/src/components/editor/editor-pane-helpers.ts@@ -9,7 +9,7 @@ import type { MemoUpdateSyncPayload } from "@/lib/local-db";import { getAttachmentLinkFromEventTarget } from "./attachment-resource-menu";import type { NoteLinkHintPosition } from "./EditorPaneChrome";-export const SUPPORTED_PASTE_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);+export { SUPPORTED_IMAGE_MIME_TYPES as SUPPORTED_PASTE_IMAGE_TYPES } from "@edgeever/shared";export const MOBILE_EDITOR_QUERY = "(max-width: 639px)";export const MOBILE_DRAFT_PERSIST_DELAY_MS = 800;diff --git a/apps/web/src/lib/desktop-resources.ts b/apps/web/src/lib/desktop-resources.tsindex 9630bb2f..ed13eae5 100644--- a/apps/web/src/lib/desktop-resources.ts+++ b/apps/web/src/lib/desktop-resources.ts@@ -1,4 +1,4 @@-import type { ResourceListItem, TiptapDoc } from "@edgeever/shared";+import { resolveResourceUploadMimeType, type ResourceListItem, type TiptapDoc } from "@edgeever/shared";import { getConfiguredDesktopApiBaseUrl } from "@/lib/api";export const isDesktopResourceRuntime = () => Boolean(typeof window !== "undefined" && window.edgeeverDesktop?.isAvailable);@@ -68,7 +68,7 @@ export const stageDesktopResource = async (memoId: string, file: File) => {const staged = await bridge.beginStagedResource({memoId,name: file.name,- type: file.type,+ type: resolveResourceUploadMimeType(file.name, file.type),size: file.size,});try {diff --git a/apps/web/src/lib/image-compression.test.mjs b/apps/web/src/lib/image-compression.test.mjsindex dde6c667..aa79204d 100644--- a/apps/web/src/lib/image-compression.test.mjs+++ b/apps/web/src/lib/image-compression.test.mjs@@ -63,3 +63,14 @@ test("terminates the worker when posting fails and retains a usable original", aexpect((await compressImageForUpload(file)).file).toBe(file);expect(terminated).toBe(true);});+++test("preserves SVG bytes and filename without starting raster compression", async () => {+ globalThis.Worker = class { constructor() { throw new Error("must not start"); } };+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 60"><rect width="100" height="60"/></svg>';+ const file = new File([svg], "diagram.svg", { type: "image/svg+xml" });+ const result = await compressImageForUpload(file);+ expect(result.file).toBe(file);+ expect(result.compressed).toBe(false);+ expect(await result.file.text()).toBe(svg);+});diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex bdbbb484..1bb31def 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -74,3 +74,5 @@ export * from "./table-operations";export * from "./poster-content-layout";export * from "./poster-operations";export * from "./infographic-operations";++export * from "./resource-media";diff --git a/packages/shared/src/resource-media.test.mjs b/packages/shared/src/resource-media.test.mjsnew file mode 100644index 00000000..bc09879a--- /dev/null+++ b/packages/shared/src/resource-media.test.mjs@@ -0,0 +1,10 @@+import { expect, test } from "bun:test";+import { resolveResourceUploadMimeType } from "./resource-media.ts";++test("recognizes SVG picker fallbacks while respecting an explicit non-image MIME", () => {+ for (const type of [null, "", "application/octet-stream", "IMAGE/SVG+XML; charset=utf-8"]) {+ expect(resolveResourceUploadMimeType("diagram.SVG", type)).toBe("image/svg+xml");+ }+ expect(resolveResourceUploadMimeType("document.svg", "text/html")).toBe("text/html");+ expect(resolveResourceUploadMimeType("archive.bin", "")).toBe("application/octet-stream");+});diff --git a/packages/shared/src/resource-media.ts b/packages/shared/src/resource-media.tsnew file mode 100644index 00000000..e17527c8--- /dev/null+++ b/packages/shared/src/resource-media.ts@@ -0,0 +1,24 @@+/** Formats rendered through an image element, never injected as document markup. */+export const SUPPORTED_IMAGE_MIME_TYPES = new Set([+ "image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/svg+xml",+]);++/** Some file pickers omit SVG MIME metadata. Do not override an explicit type. */+export const resolveResourceUploadMimeType = (filename: string, mimeType?: string | null): string => {+ const type = mimeType?.split(";")[0]?.trim().toLowerCase();+ if ((!type || type === "application/octet-stream") && /\.svg$/i.test(filename.trim())) {+ return "image/svg+xml";+ }+ return type || "application/octet-stream";+};++// SVG must also be inert when its URL is opened as a document. Keep inline styles+// and embedded images for exported diagrams, but prohibit scripts and network access.+export const SVG_RESOURCE_CONTENT_SECURITY_POLICY =+ "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox";++export const setSvgResourceSecurityHeaders = (headers: Headers): void => {+ if (headers.get("Content-Type")?.split(";")[0]?.trim().toLowerCase() === "image/svg+xml") {+ headers.set("Content-Security-Policy", SVG_RESOURCE_CONTENT_SECURITY_POLICY);+ }+};diff --git a/tests/e2e/markdown-image-paste.spec.ts b/tests/e2e/markdown-image-paste.spec.tsindex becfcf66..41a2c085 100644--- a/tests/e2e/markdown-image-paste.spec.ts+++ b/tests/e2e/markdown-image-paste.spec.ts@@ -166,3 +166,53 @@ test("shows a stable local preview while a pasted image is uploading", async ({await deleteMemo(page, memo.id);}});++for (const mimeType of ["image/svg+xml", "application/octet-stream"]) {+ test(`previews and persists a pasted SVG without rasterizing (${mimeType})`, async ({ page }) => {+ const title = `SVG upload ${Date.now()}`;+ const memo = await createMemo(page, title);+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="240" height="120" viewBox="0 0 240 120"><style>rect{fill:#07130b}</style><rect width="240" height="120"/><text x="20" y="65" fill="white">SVG preview</text><script>window.svgExecuted=true</script></svg>';+ try {+ await page.goto("/");+ await expect(page.locator(".ProseMirror[contenteditable='true']")).toBeEditable();+ await page.getByRole("button", { name: "全部笔记", exact: true }).click();+ await page.locator(`[data-memo-id="${memo.id}"]`).locator("button").first().click();+ const editor = page.locator(".ProseMirror[contenteditable='true']");+ await expect(editor).toBeEditable();+ const uploaded = page.waitForResponse((response) => response.request().method() === "POST"+ && response.url().endsWith(`/api/v1/memos/${memo.id}/resources`));+ await editor.evaluate((element, input) => {+ const clipboardData = new DataTransfer();+ clipboardData.items.add(new File([input.svg], "diagram.svg", { type: input.mimeType }));+ element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData }));+ }, { svg, mimeType });+ const { resource } = await (await uploaded).json();+ expect(resource.kind).toBe("image");+ expect(resource.mimeType).toBe("image/svg+xml");+ const image = editor.locator(`img[src="${resource.url}"]`);+ await expect(image).toBeVisible();+ await expect.poll(() => image.evaluate((node: HTMLImageElement) => node.naturalWidth)).toBe(240);+ const original = await page.request.get(resource.url);+ expect(await original.text()).toBe(svg);+ await test.info().attach("svg-preview", { body: await image.screenshot(), contentType: "image/png" });+ expect(original.headers()["content-security-policy"]).toContain("sandbox");+ await expect.poll(async () => {+ const response = await page.request.get(`/api/v1/memos/${memo.id}`);+ return JSON.stringify((await response.json()).memo.contentJson);+ }).toContain(resource.url);+ await page.reload();+ await expect(page.locator(".ProseMirror[contenteditable='true']")).toBeEditable();+ await page.getByRole("button", { name: "全部笔记", exact: true }).click();+ await page.locator(`[data-memo-id="${memo.id}"]`).locator("button").first().click();+ await expect(page.locator(`.ProseMirror img[src="${resource.url}"]`)).toBeVisible();+ // Opening the original as a document must not execute embedded scripts.+ const document = await page.context().newPage();+ try {+ await document.goto(new URL(resource.url, page.url()).href);+ expect(await document.evaluate(() => Reflect.get(window, "svgExecuted"))).toBeUndefined();+ } finally { await document.close(); }+ } finally {+ await deleteMemo(page, memo.id);+ }+ });+}