Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(link previews): store the favicon as an attachment instead of inlining it
Elian Doran5729e8ee7454
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.tsindex 989db906fe..7c19220610 100644--- a/apps/client/src/services/link_embed.spec.ts+++ b/apps/client/src/services/link_embed.spec.ts@@ -115,52 +115,60 @@ describe("fetchMetadata", () => {expect(result.unresolved).toBe(true);});- describe("image offload to attachment", () => {+ describe("picture offload to attachments", () => {const metaWithDataUriImage = {url: "https://example.com",embedType: "opengraph",title: "Title",- favicon: "data:image/png;base64,FAV",+ favicon: "data:image/x-icon;base64,FAV",image: "data:image/jpeg;base64,IMG"};- it("stores the image as an attachment of the owning note, keeping the favicon inline", async () => {+ it("stores both the card image and the favicon as attachments of the owning note", async () => {server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;- uploadImageAttachmentMock.mockResolvedValueOnce("api/attachments/att1/image/image.jpg");+ uploadImageAttachmentMock+ .mockResolvedValueOnce("api/attachments/att1/image/favicon.ico")+ .mockResolvedValueOnce("api/attachments/att2/image/image.jpg");const result = await fetchMetadata("https://example.com", "note1");- expect(uploadImageAttachmentMock).toHaveBeenCalledExactlyOnceWith("note1", "data:image/jpeg;base64,IMG");- // Only the attachment URL lands in the note content — inlined base64 would count against- // the auto-read-only size threshold. The favicon stays inline: it is small and shared- // with inline mentions.- expect(result.image).toBe("api/attachments/att1/image/image.jpg");- expect(result.favicon).toBe("data:image/png;base64,FAV");+ expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/x-icon;base64,FAV");+ expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/jpeg;base64,IMG");+ // Only the attachment URLs land in the note content — inlined base64 counts against the+ // auto-read-only size threshold, and a favicon pays that cost once per link rather than+ // once per note.+ expect(result.favicon).toBe("api/attachments/att1/image/favicon.ico");+ expect(result.image).toBe("api/attachments/att2/image/image.jpg");});it("keeps the data URI when the upload fails, so the preview still persists", async () => {server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;- uploadImageAttachmentMock.mockResolvedValueOnce(null);+ uploadImageAttachmentMock.mockResolvedValue(null);const result = await fetchMetadata("https://example.com", "note1");expect(result.image).toBe("data:image/jpeg;base64,IMG");+ expect(result.favicon).toBe("data:image/x-icon;base64,FAV");});- it("does not upload without an owning note, a non-data-URI image, or a missing image", async () => {+ it("does not upload without an owning note, a non-data-URI picture, or a missing one", async () => {uploadImageAttachmentMock.mockClear();server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;const withoutNote = await fetchMetadata("https://example.com");expect(withoutNote.image).toBe("data:image/jpeg;base64,IMG");-- server.post = vi.fn(async () => ({ ...metaWithDataUriImage, image: "https://img.example/x.png" })) as typeof server.post;- const remoteImage = await fetchMetadata("https://example.com", "note1");- expect(remoteImage.image).toBe("https://img.example/x.png");-- server.post = vi.fn(async () => ({ ...metaWithDataUriImage, image: undefined })) as typeof server.post;- const noImage = await fetchMetadata("https://example.com", "note1");- expect(noImage.image).toBeUndefined();+ expect(withoutNote.favicon).toBe("data:image/x-icon;base64,FAV");++ const remote = { ...metaWithDataUriImage, image: "https://img.example/x.png", favicon: "https://img.example/f.ico" };+ server.post = vi.fn(async () => remote) as typeof server.post;+ const remotePictures = await fetchMetadata("https://example.com", "note1");+ expect(remotePictures.image).toBe("https://img.example/x.png");+ expect(remotePictures.favicon).toBe("https://img.example/f.ico");++ server.post = vi.fn(async () => ({ ...metaWithDataUriImage, image: undefined, favicon: undefined })) as typeof server.post;+ const noPictures = await fetchMetadata("https://example.com", "note1");+ expect(noPictures.image).toBeUndefined();+ expect(noPictures.favicon).toBeUndefined();expect(uploadImageAttachmentMock).not.toHaveBeenCalled();});diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsxindex e8590ffad3..ffe017507d 100644--- a/apps/client/src/services/link_embed.tsx+++ b/apps/client/src/services/link_embed.tsx@@ -33,24 +33,35 @@ export function safeHostname(url: string): string {* Fetches link metadata from the server. Called once at link creation time.* The returned metadata is then stored in the note's HTML as data attributes.*- * When `ownerNoteId` is given, the preview image is stored as an attachment of that note and only- * its `api/attachments/...` URL ends up in the metadata. Inlined as a base64 data URI it would be- * 10–140KB of note content per preview — enough for a single card to push the note past the- * `autoReadonlySizeText` threshold (32KB by default) and flip it read-only.+ * When `ownerNoteId` is given, both pictures a preview carries — the card image and the favicon —+ * are stored as attachments of that note, and only their `api/attachments/...` URLs end up in the+ * metadata. Inlined as base64 data URIs they are 10–140KB of note content for a card image and+ * 1–10KB for a favicon, and that lands in the note's HTML, where it is synced and revisioned like+ * any other content. A single card is enough to push a note past the `autoReadonlySizeText`+ * threshold (32KB by default) and flip it read-only; favicons get there by repetition instead,+ * since a note that links a site once usually links it many times and each copy carries the icon+ * again.*/export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<EmbedMetadata> {try {// POSTed rather than passed in the query string: a URL can carry a one-time token or a// signed signature, and a query string ends up in every access log along the way.const metadata = await server.post<LinkEmbedMetadata>("link-embed/metadata", { url });+ // Uploaded together: they are two independent requests and a preview needs both before it+ // can be stored.+ const [ favicon, image ] = await Promise.all([+ offloadPictureToAttachment(metadata.favicon, ownerNoteId),+ offloadPictureToAttachment(metadata.image, ownerNoteId)+ ]);+return {url: metadata.url,embedType: metadata.embedType,title: metadata.title,description: metadata.description,- favicon: metadata.favicon,+ favicon,siteName: metadata.siteName,- image: await offloadImageToAttachment(metadata.image, ownerNoteId),+ image,unresolved: metadata.unresolved};} catch {@@ -64,19 +75,19 @@ export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<}/**- * Converts a base64 preview image into an attachment of the owning note, returning its- * `api/attachments/...` URL — or the data URI unchanged when the upload fails, so the preview- * still persists and renders, just at the old inline cost.+ * Converts one of a preview's base64 pictures into an attachment of the owning note, returning its+ * `api/attachments/...` URL — or the data URI unchanged when the upload fails, so the preview still+ * persists and renders, just at the old inline cost.*- * Only the card image is offloaded. The favicon stays inline on purpose: it is a few KB, and it is- * carried by inline mentions too, where an attachment per mention would flood the attachment list.+ * Both pictures go through this, so both are subject to the same rule at the render sinks: only an+ * inline image or an attachment of this instance is ever loaded (see `isLocalPreviewImageSrc`).*/-async function offloadImageToAttachment(image: string | undefined, ownerNoteId: string | undefined): Promise<string | undefined> {- if (!image || !ownerNoteId || !image.startsWith("data:")) {- return image;+async function offloadPictureToAttachment(picture: string | undefined, ownerNoteId: string | undefined): Promise<string | undefined> {+ if (!picture || !ownerNoteId || !picture.startsWith("data:")) {+ return picture;}- return await uploadImageAttachment(ownerNoteId, image) ?? image;+ return await uploadImageAttachment(ownerNoteId, picture) ?? picture;}// ---------------------------------------------------------------------------@@ -206,8 +217,8 @@ function EmbedPreview({ meta, editable }: { meta: EmbedMetadata; editable?: bool{meta.title && <div className="link-embed-card-title">{meta.title}</div>}{meta.description && <div className="link-embed-card-description">{meta.description}</div>}<div className="link-embed-card-url">- {/* The same favicon the inline mention shows, read from the metadata already stored- on the element — the data URI is not duplicated. */}+ {/* The same favicon the inline mention shows, read from the metadata already+ stored on the element. */}<Favicon src={meta.favicon} /><span>{meta.siteName || safeHostname(meta.url)}</span></div>diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.tsindex 60d457d104..d521ac2469 100644--- a/apps/server/src/routes/api/link_embed.spec.ts+++ b/apps/server/src/routes/api/link_embed.spec.ts@@ -47,6 +47,22 @@ async function makePng(width: number, height: number, color: number) {return Buffer.from(await image.getBuffer("image/png"));}+/**+ * A real icon directory of one entry, since a favicon is now named by what its bytes say it is+ * rather than by the content type the site served it under.+ */+function makeIco(): Buffer {+ const directory = Buffer.alloc(22);+ directory.writeUInt16LE(1, 2); // type: icon+ directory.writeUInt16LE(1, 4); // one entry+ directory.writeUInt8(16, 6); // width+ directory.writeUInt8(16, 7); // height+ directory.writeUInt32LE(4, 14); // payload length+ directory.writeUInt32LE(directory.length, 18); // where the payload starts++ return Buffer.concat([ directory, Buffer.from([ 0, 0, 0, 0 ]) ]);+}+/** Decodes a `data:` URI back into its media type and bytes. */function parseDataUri(dataUri: string) {const match = /^data:([^;]+);base64,(.+)$/.exec(dataUri);@@ -74,7 +90,7 @@ describe("link-embed getMetadata", () => {it("returns YouTube metadata via the oEmbed endpoint", async () => {safeFetch.mockImplementation(async (url: string) => {- if (url.includes("favicon")) return fakeResponse(Buffer.from([1, 2, 3]), { contentType: "image/x-icon" });+ if (url.includes("favicon")) return fakeResponse(makeIco(), { contentType: "image/x-icon" });return fakeResponse("", { json: { title: "Cool Video", author_name: "Channel", thumbnail_url: "https://img/thumb.jpg" } });});@@ -95,7 +111,7 @@ describe("link-embed getMetadata", () => {</head></html>`;const png = await makePng(40, 20, 0xff0000ff);safeFetch.mockImplementation(async (url: string) => {- if (url.includes("fav.ico")) return fakeResponse(Buffer.from([9, 9]), { contentType: "image/x-icon" });+ if (url.includes("fav.ico")) return fakeResponse(makeIco(), { contentType: "image/x-icon" });if (url.includes("img.png")) return fakeResponse(png, { contentType: "image/png" });return fakeResponse(html, { contentType: "text/html" });});@@ -310,7 +326,7 @@ describe("link-embed getMetadata", () => {it("uses a generic YouTube title when oEmbed is unavailable", async () => {safeFetch.mockImplementation(async (url: string) => {- if (url.includes("favicon")) return fakeResponse(Buffer.from([1]), { contentType: "image/x-icon" });+ if (url.includes("favicon")) return fakeResponse(makeIco(), { contentType: "image/x-icon" });return fakeResponse("", { ok: false }); // oembed fails});const result = await linkEmbedRoute.getMetadata(req("https://youtu.be/dQw4w9WgXcQ"));@@ -363,6 +379,31 @@ describe("link-embed getMetadata", () => {expect(result.favicon).toBeUndefined();});+ it("names a favicon by its own bytes rather than by the content type it was served under", async () => {+ const html = `<html><head><title>Plain</title><link rel="icon" href="/fav.ico"></head></html>`;+ // Serving favicon.ico as an octet-stream is common enough to be the normal case on some+ // hosts. The media type decides whether the client's upload of it is stored as a picture at+ // all, so taking the header's word for it would leave the icon as a file attachment, which+ // comes back as a `#root/...` reference the render sinks reject.+ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("fav.ico")) return fakeResponse(makeIco(), { contentType: "application/octet-stream" });+ return fakeResponse(html, { contentType: "text/html" });+ });++ let result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(parseDataUri(result.favicon ?? "").contentType).toBe("image/x-icon");++ // And the same reading in the other direction: an error page served where the icon should+ // be is not made into one by a content type claiming it is.+ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("fav.ico")) return fakeResponse("<html>Not found</html>", { contentType: "image/x-icon" });+ return fakeResponse(html, { contentType: "text/html" });+ });++ result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result.favicon).toBeUndefined();+ });+it("keeps the preview when the favicon download throws or has no body", async () => {const html = `<html><head><title>Plain</title><link rel="icon" href="/fav.ico"></head></html>`;@@ -432,7 +473,7 @@ describe("link-embed getMetadata", () => {safeFetch.mockImplementation(async (url: string) => {if (url.includes("oembed")) return fakeResponse("", { json: {} });if (url.includes("hqdefault.jpg")) return fakeResponse(thumb, { contentType: "image/jpeg" });- if (url.includes("favicon")) return fakeResponse(Buffer.from([1]), { contentType: "image/x-icon" });+ if (url.includes("favicon")) return fakeResponse(makeIco(), { contentType: "image/x-icon" });return fakeResponse("", { ok: false });});@@ -462,7 +503,7 @@ describe("link-embed getMetadata", () => {const html = `<html><head><title>Plain</title><link rel="icon" href="/big.ico"></head></html>`;safeFetch.mockImplementation(async (url: string) => {if (url.includes("big.ico")) {- const big = fakeResponse(Buffer.from([1, 2, 3]), { contentType: "image/x-icon" });+ const big = fakeResponse(makeIco(), { contentType: "image/x-icon" });(big.headers as { get: (h: string) => string | null }).get = (h: string) =>h.toLowerCase() === "content-length" ? String(1024 * 1024) : "image/x-icon";return big;diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.tsindex 0d67bb7f91..cd1cda1f3c 100644--- a/apps/server/src/routes/api/link_embed.ts+++ b/apps/server/src/routes/api/link_embed.ts@@ -5,6 +5,7 @@ import isSvg from "is-svg";import { Jimp } from "jimp";import { parse } from "node-html-parser";+import { getImageTypeFromBuffer } from "../../services/image_codec.js";import { safeFetch, validateUrl } from "../../services/safe_fetch.js";const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB@@ -101,14 +102,33 @@ function toDataUri(contentType: string, buffer: Buffer): string {}/**- * Downloads a favicon and returns it as a base64 data URI.- * Returns undefined if the download fails or the image is too large.+ * The media type to name a downloaded picture by, read from its own bytes, or undefined when the+ * bytes are not a picture at all.+ *+ * The response header cannot answer this. `favicon.ico` is routinely served as+ * `application/octet-stream` or `text/plain`, and the media type is not decoration: the client+ * offloads these into attachments, and the upload endpoint decides whether it is storing a picture+ * from the type the data URI declares. A favicon named by a careless header would be stored as a+ * file, come back as a `#root/...` reference, and be rejected at the render sink.+ *+ * Undefined also covers the case the header hides in the other direction — an HTML error page+ * served in place of an image, which is not something to keep whatever it claims to be.+ */+async function detectImageMime(buffer: Buffer): Promise<string | undefined> {+ return (await getImageTypeFromBuffer(buffer))?.mime;+}++/**+ * Downloads a favicon and returns it as a base64 data URI, named by its own bytes.+ * Returns undefined if the download fails, the image is too large, or it is not an image.*/async function downloadFaviconAsDataUri(faviconUrl: string): Promise<string | undefined> {const downloaded = await downloadBinary(faviconUrl, MAX_FAVICON_SIZE, "image/x-icon");if (!downloaded) return undefined;- return toDataUri(downloaded.contentType, downloaded.buffer);+ const mime = await detectImageMime(downloaded.buffer);++ return mime ? toDataUri(mime, downloaded.buffer) : undefined;}/**@@ -160,16 +180,18 @@ async function downloadImageAsDataUri(imageUrl: string, minSourceDimension = 0):} catch (e: unknown) {// Jimp bundles decoders for PNG/JPEG/GIF/BMP/TIFF only, so a WebP or AVIF lands here. Keep// the original bytes when they are small enough — unresized, but still not hotlinked. The- // content type is checked so that an error page served in place of the image (an undecodable- // response that is not an image at all) is dropped rather than embedded. A caller that- // requires a minimum size gets nothing: undecodable means unverifiable.+ // bytes are asked what they are, the same way a favicon's are, so that an error page served+ // in place of the image (an undecodable response that is not an image at all) is dropped+ // rather than embedded. A caller that requires a minimum size gets nothing: undecodable+ // means unverifiable.// The URL is deliberately left out of the log: it is the user's private browsing, and a// pasted link can carry a one-time token in its path or query. The timestamp is enough to// match a log line against the paste that caused it.getLog().info(`Could not decode a link preview image: ${e}`);- return isSmallEnoughToKeepVerbatim && contentType.startsWith("image/") && !minSourceDimension- ? toDataUri(contentType, buffer)- : undefined;++ const mime = isSmallEnoughToKeepVerbatim && !minSourceDimension ? await detectImageMime(buffer) : undefined;++ return mime ? toDataUri(mime, buffer) : undefined;}}diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.tsindex ca46d6ee6d..94bae97160 100644--- a/apps/server/src/services/notes.spec.ts+++ b/apps/server/src/services/notes.spec.ts@@ -113,18 +113,41 @@ describe("checkImageAttachments", () => {expect(att.save).not.toHaveBeenCalled();});- it("keeps attachments referenced from a link preview's data-image attribute alive", () => {- const note = buildNote({ title: "Test", attachments: [{ title: "image.jpg", role: "image", mime: "image/jpeg" }] });+ it("keeps attachments referenced from a link preview's picture attributes alive", () => {+ const note = buildNote({+ title: "Test",+ attachments: [+ { title: "image.jpg", role: "image", mime: "image/jpeg" },+ { title: "favicon.ico", role: "image", mime: "image/x-icon" }+ ]+ });mockAttachmentSaves(note);- const [att] = note.getAttachments();- att.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";+ const [ image, favicon ] = note.getAttachments();+ image.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";+ favicon.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";++ // A link preview carries both of its pictures in data attributes, not in an <img src>:+ // the card image, and the favicon an inline mention shows on its own.+ const content = `<section class="link-embed" data-url="https://example.com"`+ + ` data-image="api/attachments/${image.attachmentId}/image/image.jpg"`+ + ` data-favicon="api/attachments/${favicon.attachmentId}/image/favicon.ico"></section>`;+ checkImageAttachments(note, content);- // A link preview carries its card image in a data attribute, not an <img src>.- const content = `<section class="link-embed" data-url="https://example.com"` +- ` data-image="api/attachments/${att.attachmentId}/image/image.jpg"></section>`;+ expect(image.utcDateScheduledForErasureSince).toBeNull();+ expect(favicon.utcDateScheduledForErasureSince).toBeNull();+ });++ it("keeps a mention's favicon alive, which is all an inline mention carries", () => {+ const note = buildNote({ title: "Test", attachments: [{ title: "favicon.ico", role: "image", mime: "image/x-icon" }] });+ mockAttachmentSaves(note);+ const [ favicon ] = note.getAttachments();+ favicon.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";++ const content = `<span class="link-mention" data-url="https://example.com"`+ + ` data-favicon="api/attachments/${favicon.attachmentId}/image/favicon.ico"></span>`;checkImageAttachments(note, content);- expect(att.utcDateScheduledForErasureSince).toBeNull();+ expect(favicon.utcDateScheduledForErasureSince).toBeNull();});it("schedules unreferenced attachments for erasure", () => {diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.tsindex 592b9573c2..d8b18f5211 100644--- a/packages/commons/src/lib/link_embed.ts+++ b/packages/commons/src/lib/link_embed.ts@@ -44,10 +44,11 @@ export function safeLinkPreviewHref(url: string | undefined | null): string {** The metadata pipeline never produces anything else. The server downloads the favicon and the card* image itself and hands back base64 `data:` URIs, precisely so that the note carries the picture- * instead of hotlinking the origin site; the client then offloads the larger card image into an- * attachment and stores its `api/attachments/…` URL. So a *remote* URL in `data-favicon` /- * `data-image` is illegitimate by construction — the mirror image of the {@link isHttpUrl} rule for- * `data-url`, where http(s) is the only legitimate case.+ * instead of hotlinking the origin site; the client then offloads both into attachments and stores+ * their `api/attachments/…` URLs, leaving the inline form only for a preview whose upload failed+ * and for notes written before that. So a *remote* URL in `data-favicon` / `data-image` is+ * illegitimate by construction — the mirror image of the {@link isHttpUrl} rule for `data-url`,+ * where http(s) is the only legitimate case.** That matters because those attributes reach an `<img src>` that fires on page load with no click,* and `data-*` survives both sanitizers untouched (see {@link isHttpUrl}), so a note arriving bydiff --git a/packages/trilium-core/src/services/export/single.spec.ts b/packages/trilium-core/src/services/export/single.spec.tsindex 41c78078ca..0d469a08f5 100644--- a/packages/trilium-core/src/services/export/single.spec.ts+++ b/packages/trilium-core/src/services/export/single.spec.ts@@ -38,9 +38,10 @@ describe("Note type mappings", () => {}});- it("inlines a link preview's data-image attachment as base64 in single-note HTML export", () => {- // A link preview references its card image attachment from `data-image`, not an <img src>;- // the single-file export must inline it the same way to stay self-contained.+ it("inlines both of a link preview's picture attachments as base64 in single-note HTML export", () => {+ // A link preview references its card image and its favicon from `data-image` and+ // `data-favicon`, not from an <img src>; the single-file export must inline both the same+ // way to stay self-contained.const note = buildNote({ type: "text", title: "Preview" });const fakeAttachment = {mime: "image/jpeg",@@ -50,11 +51,14 @@ describe("Note type mappings", () => {try {const content = `<section class="link-embed" data-url="https://example.com"`- + ` data-image="api/attachments/att1/image/preview.jpg"></section>`;+ + ` data-image="api/attachments/att1/image/preview.jpg"`+ + ` data-favicon="api/attachments/att2/image/favicon.ico"></section>`;const { payload } = mapByNoteType(note, content, "html");expect(getAttachment).toHaveBeenCalledWith("att1");+ expect(getAttachment).toHaveBeenCalledWith("att2");expect(payload).toContain(`data-image="data:image/jpeg;base64,AQID"`);+ expect(payload).toContain(`data-favicon="data:image/jpeg;base64,AQID"`);expect(payload).not.toContain("api/attachments");} finally {getAttachment.mockRestore();diff --git a/packages/trilium-core/src/services/export/single.ts b/packages/trilium-core/src/services/export/single.tsindex fedd72a957..d05c41e8f4 100644--- a/packages/trilium-core/src/services/export/single.ts+++ b/packages/trilium-core/src/services/export/single.ts@@ -140,9 +140,10 @@ function inlineAttachments(content: string) {return `src="${srcValue}"`;});- // `data-image` is where link previews (section.link-embed) keep their card image reference;- // inlining it keeps the exported file self-contained just like an <img> src.- content = content.replace(/(src|data-image)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/?[^"]+"/g, (match, attrName, attachmentId) => {+ // `data-image` and `data-favicon` are where link previews (section.link-embed,+ // span.link-mention) keep their two picture references; inlining them keeps the exported file+ // self-contained just like an <img> src.+ content = content.replace(/(src|data-image|data-favicon)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/?[^"]+"/g, (match, attrName, attachmentId) => {const attachment = becca.getAttachment(attachmentId);if (!attachment || !attachment.mime.startsWith("image/")) {return match;diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.tsindex 374c210c31..19104debd4 100644--- a/packages/trilium-core/src/services/export/zip.spec.ts+++ b/packages/trilium-core/src/services/export/zip.spec.ts@@ -357,27 +357,34 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {}});- it("rewrites a link preview's data-image reference to the exported attachment file", async () => {- // A link preview stores its card image as an attachment referenced from `data-image`- // (not an <img src>), so the attribute must be rewritten to the exported attachment- // file just like an image src. The markdown export keeps the preview's raw HTML, so- // the same rewrite must land there too.+ it("rewrites a link preview's picture references to the exported attachment files", async () => {+ // A link preview stores its card image and its favicon as attachments referenced from+ // `data-image` and `data-favicon` (not an <img src>), so both attributes must be+ // rewritten to the exported attachment files just like an image src. The markdown+ // export keeps the preview's raw HTML, so the same rewrite must land there too.const { note } = createNote("root", { title: "LinkPreviewHost", content: "" });getContext().init(() => {- const attachment = note.saveAttachment({ role: "image", mime: "image/jpeg", title: "preview.jpg", content: "jpeg-bytes" });+ const image = note.saveAttachment({ role: "image", mime: "image/jpeg", title: "preview.jpg", content: "jpeg-bytes" });+ const favicon = note.saveAttachment({ role: "image", mime: "image/x-icon", title: "favicon.ico", content: "ico-bytes" });note.setContent(`<section class="link-embed" data-url="https://example.com" data-embed-type="opengraph"` +- ` data-title="Example" data-image="api/attachments/${attachment.attachmentId}/image/preview.jpg"></section>`);+ ` data-title="Example" data-image="api/attachments/${image.attachmentId}/image/preview.jpg"` ++ ` data-favicon="api/attachments/${favicon.attachmentId}/image/favicon.ico"></section>`);});for (const format of ["html", "markdown"] as const) {const { entries } = await exportSubtree(note.getParentBranches()[0], format);const rootMeta = parseMeta(entries).files[0];+ const attachments = rootMeta.attachments ?? [];- const attFileName = (rootMeta.attachments ?? [])[0]?.dataFileName ?? "";- expect(entries[attFileName], format).toBeDefined();+ const fileNameOf = (title: string) => attachments.find((a) => a.title === title)?.dataFileName ?? "";+ const imageFileName = fileNameOf("preview.jpg");+ const faviconFileName = fileNameOf("favicon.ico");+ expect(entries[imageFileName], format).toBeDefined();+ expect(entries[faviconFileName], format).toBeDefined();const exported = entries[rootMeta.dataFileName ?? ""].toString("utf-8");- expect(exported, format).toContain(`data-image="${attFileName}"`);+ expect(exported, format).toContain(`data-image="${imageFileName}"`);+ expect(exported, format).toContain(`data-favicon="${faviconFileName}"`);expect(exported, format).not.toContain("api/attachments");}});diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.tsindex eeecc88d0b..b99653a7d4 100644--- a/packages/trilium-core/src/services/export/zip.ts+++ b/packages/trilium-core/src/services/export/zip.ts@@ -274,9 +274,10 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,return url ? `src="${url}"` : match;});- // `data-image` is where link previews (section.link-embed / span.link-mention) keep their- // card image reference; it points at the exported attachment file just like an <img> src.- content = content.replace(/(src|data-image)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/[^"]*"/g, (match, attrName, targetAttachmentId) => {+ // `data-image` and `data-favicon` are where link previews (section.link-embed /+ // span.link-mention) keep their two picture references; both point at the exported+ // attachment file just like an <img> src.+ content = content.replace(/(src|data-image|data-favicon)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/[^"]*"/g, (match, attrName, targetAttachmentId) => {const url = findAttachment(targetAttachmentId);return url ? `${attrName}="${url}"` : match;diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex bc91299f2d..19765c4253 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -464,9 +464,11 @@ export function checkImageAttachments(note: BNote, content: string) {: [// <img src="api/attachments/{id}/image/...">/src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,- // Link previews reference their card image from a data attribute, not an <img>:- // <section class="link-embed" data-image="api/attachments/{id}/image/...">- /data-image="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,+ // Link previews reference both of their pictures from data attributes rather than+ // from an <img>: the card image, and the favicon that an inline mention carries on+ // its own. <section class="link-embed" data-image="api/attachments/{id}/image/..."+ // data-favicon="api/attachments/{id}/image/...">+ /data-(?:image|favicon)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,// <a href="...attachmentId={id}">/href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g];