Skip to content

Build your personal knowledge base with Trilium Notes

link previews: embed images into markup, re-encode/resize images on server-side

Adorian Doran4ce315237e6e
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.ts
index 236d4d1301..a3c84c9e17 100644
--- a/apps/server/src/routes/api/link_embed.spec.ts
+++ b/apps/server/src/routes/api/link_embed.spec.ts
@@ -1,6 +1,7 @@
import { extractYouTubeVideoId } from "@triliumnext/commons";
import { ValidationError } from "@triliumnext/core";
import type { Request } from "express";
+import { Jimp } from "jimp";
import { describe, expect, it, vi } from "vitest";
const safeFetch = vi.hoisted(() => vi.fn());
@@ -40,6 +41,19 @@ function fakeResponse(payload: string | Buffer, opts: { ok?: boolean; contentTyp
};
}
+/** A real, decodable PNG so the image pipeline runs for true rather than against a mock. */
+async function makePng(width: number, height: number, color: number) {
+ const image = new Jimp({ width, height, color });
+ return Buffer.from(await image.getBuffer("image/png"));
+}
+
+/** Decodes a `data:` URI back into its media type and bytes. */
+function parseDataUri(dataUri: string) {
+ const match = /^data:([^;]+);base64,(.+)$/.exec(dataUri);
+ if (!match) throw new Error(`Not a base64 data URI: ${dataUri.slice(0, 40)}`);
+ return { contentType: match[1], buffer: Buffer.from(match[2], "base64") };
+}
+
describe("extractYouTubeVideoId", () => {
it("extracts ids and rejects non-YouTube URLs", () => {
expect(extractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
@@ -76,8 +90,10 @@ describe("link-embed getMetadata", () => {
<meta property="og:site_name" content="Example">
<link rel="icon" href="/fav.ico">
</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("img.png")) return fakeResponse(png, { contentType: "image/png" });
return fakeResponse(html, { contentType: "text/html" });
});
@@ -86,25 +102,110 @@ describe("link-embed getMetadata", () => {
expect(result.title).toBe("OG Title");
expect(result.description).toBe("OG Desc");
expect(result.siteName).toBe("Example");
- expect(result.image).toBe("https://site/img.png");
+ // Embedded, not hotlinked; opaque, so re-encoded as JPEG.
+ expect(result.image).toMatch(/^data:image\/jpeg;base64,/);
});
- it("resolves a relative og:image against the page URL", async () => {
+ it("resolves a relative og:image against the page URL before downloading it", async () => {
// A relative or protocol-relative og:image would otherwise be resolved against Trilium's own
- // origin when the card renders, silently yielding a broken image.
+ // origin, so the image would be downloaded from the wrong place (or not at all).
const page = (image: string) => `<html><head><title>T</title><meta property="og:image" content="${image}"></head></html>`;
- const imageFor = async (image: string) => {
- safeFetch.mockResolvedValue(fakeResponse(page(image), { contentType: "text/html" }));
- const result = await linkEmbedRoute.getMetadata(req("https://example.com/blog/post"));
- return result.image;
+ const png = await makePng(10, 10, 0xff0000ff);
+
+ const requestedImageUrl = async (image: string) => {
+ safeFetch.mockReset();
+ safeFetch.mockImplementation(async (url: string) => {
+ if (url.endsWith(".png")) return fakeResponse(png, { contentType: "image/png" });
+ return fakeResponse(page(image), { contentType: "text/html" });
+ });
+ await linkEmbedRoute.getMetadata(req("https://example.com/blog/post"));
+ return safeFetch.mock.calls.map((call) => call[0]).find((url: string) => url.endsWith(".png"));
};
- expect(await imageFor("/img/cover.png")).toBe("https://example.com/img/cover.png");
- expect(await imageFor("cover.png")).toBe("https://example.com/blog/cover.png");
- expect(await imageFor("//cdn.example.com/cover.png")).toBe("https://cdn.example.com/cover.png");
- expect(await imageFor("https://cdn.example.com/cover.png")).toBe("https://cdn.example.com/cover.png");
- // Malformed enough that it cannot form a URL even against a valid base.
- expect(await imageFor("http://[")).toBeUndefined();
+ expect(await requestedImageUrl("/img/cover.png")).toBe("https://example.com/img/cover.png");
+ expect(await requestedImageUrl("cover.png")).toBe("https://example.com/blog/cover.png");
+ expect(await requestedImageUrl("//cdn.example.com/cover.png")).toBe("https://cdn.example.com/cover.png");
+ expect(await requestedImageUrl("https://cdn.example.com/cover.png")).toBe("https://cdn.example.com/cover.png");
+ // Malformed enough that it cannot form a URL even against a valid base: never downloaded.
+ expect(await requestedImageUrl("http://[")).toBeUndefined();
+ });
+
+ describe("preview image embedding", () => {
+ /** Serves `image` for the og:image URL, and a minimal page pointing at it for anything else. */
+ function serveImage(image: { payload: string | Buffer; contentType: string; ok?: boolean }) {
+ const html = `<html><head><title>T</title><meta property="og:image" content="/cover"></head></html>`;
+ safeFetch.mockImplementation(async (url: string) => {
+ if (url.endsWith("/cover")) return fakeResponse(image.payload, { contentType: image.contentType, ok: image.ok });
+ return fakeResponse(html, { contentType: "text/html" });
+ });
+ }
+
+ async function imageOf() {
+ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
+ // The rest of the preview must survive whatever happens to the image.
+ expect(result.title).toBe("T");
+ return result.image;
+ }
+
+ it("scales an oversized image down to the 256px limit, preserving the aspect ratio", async () => {
+ serveImage({ payload: await makePng(1024, 512, 0x00ff00ff), contentType: "image/png" });
+
+ const image = await imageOf();
+ expect(image).toMatch(/^data:image\/jpeg;base64,/);
+
+ const decoded = await Jimp.read(parseDataUri(image ?? "").buffer);
+ expect(decoded.bitmap.width).toBe(256);
+ expect(decoded.bitmap.height).toBe(128);
+ });
+
+ it("keeps transparency by re-encoding a transparent image as PNG", async () => {
+ serveImage({ payload: await makePng(400, 400, 0x00000000), contentType: "image/png" });
+
+ const image = await imageOf();
+ expect(image).toMatch(/^data:image\/png;base64,/);
+
+ const decoded = await Jimp.read(parseDataUri(image ?? "").buffer);
+ expect(decoded.bitmap.width).toBe(256);
+ expect(decoded.hasAlpha()).toBe(true);
+ });
+
+ it("does not enlarge an image that is already smaller than the limit", async () => {
+ serveImage({ payload: await makePng(64, 32, 0xff0000ff), contentType: "image/png" });
+
+ const decoded = await Jimp.read(parseDataUri(await imageOf() ?? "").buffer);
+ expect(decoded.bitmap.width).toBe(64);
+ expect(decoded.bitmap.height).toBe(32);
+ });
+
+ it("embeds an SVG verbatim, but drops one over 200KB", async () => {
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>`;
+ serveImage({ payload: svg, contentType: "image/svg+xml" });
+ expect(parseDataUri(await imageOf() ?? "")).toMatchObject({ contentType: "image/svg+xml" });
+
+ const hugeSvg = svg.replace("<rect", `<!--${"x".repeat(200 * 1024)}--><rect`);
+ serveImage({ payload: hugeSvg, contentType: "image/svg+xml" });
+ expect(await imageOf()).toBeUndefined();
+ });
+
+ it("keeps an undecodable image format (WebP, AVIF) verbatim when it is small enough", async () => {
+ // Jimp bundles no WebP decoder, so these bytes cannot be resized — but they must still not
+ // be hotlinked. Anything over the verbatim cap is dropped instead.
+ serveImage({ payload: Buffer.from("RIFF????WEBPVP8 not-really"), contentType: "image/webp" });
+ expect(await imageOf()).toMatch(/^data:image\/webp;base64,/);
+
+ serveImage({ payload: Buffer.alloc(300 * 1024, 1), contentType: "image/webp" });
+ expect(await imageOf()).toBeUndefined();
+ });
+
+ it("drops the image, keeping the rest of the preview, when it cannot be fetched", async () => {
+ serveImage({ payload: "", contentType: "image/png", ok: false });
+ expect(await imageOf()).toBeUndefined();
+ });
+
+ it("does not embed a non-image response served in place of the image", async () => {
+ serveImage({ payload: "<html>404</html>", contentType: "text/html" });
+ expect(await imageOf()).toBeUndefined();
+ });
});
it("falls back to the hostname when the fetch fails, flagging the result unresolved", async () => {
diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.ts
index 549ba082b1..2a03bc1239 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/apps/server/src/routes/api/link_embed.ts
@@ -1,6 +1,8 @@
import { extractYouTubeVideoId, type LinkEmbedMetadata } from "@triliumnext/commons";
import { getLog, ValidationError } from "@triliumnext/core";
import type { Request } from "express";
+import isSvg from "is-svg";
+import { Jimp } from "jimp";
import { parse } from "node-html-parser";
import { safeFetch, validateUrl } from "../../services/safe_fetch.js";
@@ -8,6 +10,18 @@ import { safeFetch, validateUrl } from "../../services/safe_fetch.js";
const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB
const MAX_FAVICON_SIZE = 64 * 1024; // 64KB
+/** Longest edge of the preview image kept in the note; larger images are scaled down to fit. */
+const IMAGE_MAX_DIMENSION = 256;
+/** Quality used when re-encoding an opaque preview image to JPEG. */
+const IMAGE_JPEG_QUALITY = 75;
+/** Refuse to even decode a preview image larger than this. */
+const MAX_IMAGE_DOWNLOAD_SIZE = 5 * 1024 * 1024; // 5MB
+/**
+ * Cap for an image kept byte-for-byte instead of being re-encoded — an SVG (which scales natively,
+ * so rasterising it would only lose quality) or a format Jimp cannot decode (WebP, AVIF).
+ */
+const MAX_VERBATIM_IMAGE_SIZE = 200 * 1024; // 200KB
+
/**
* Reads the response body as text, stopping after maxBytes to avoid
* buffering arbitrarily large responses into memory.
@@ -33,20 +47,21 @@ async function readResponseText(response: Response, maxBytes: number): Promise<s
}
/**
- * Downloads a favicon and returns it as a base64 data URI.
- * Returns undefined if the download fails or the image is too large.
+ * Downloads a binary resource, refusing anything over `maxBytes` — both up front, when the server
+ * advertises the size, and while streaming, when it does not.
+ * Returns undefined if the download fails or the resource is too large.
*/
-async function downloadFaviconAsDataUri(faviconUrl: string): Promise<string | undefined> {
+async function downloadBinary(url: string, maxBytes: number, defaultContentType: string): Promise<{ buffer: Buffer; contentType: string } | undefined> {
try {
- const response = await safeFetch(faviconUrl);
+ const response = await safeFetch(url);
if (!response.ok) return undefined;
// Bail early if the server advertises a size over the limit
const contentLength = response.headers.get("content-length");
- if (contentLength && parseInt(contentLength, 10) > MAX_FAVICON_SIZE) return undefined;
+ if (contentLength && parseInt(contentLength, 10) > maxBytes) return undefined;
- const contentType = response.headers.get("content-type") || "image/x-icon";
+ const contentType = (response.headers.get("content-type") || defaultContentType).split(";")[0];
// Stream the body and enforce the size limit during download
const reader = response.body?.getReader();
@@ -60,21 +75,84 @@ async function downloadFaviconAsDataUri(faviconUrl: string): Promise<string | un
if (done) break;
bytesRead += value.byteLength;
- if (bytesRead > MAX_FAVICON_SIZE) {
+ if (bytesRead > maxBytes) {
void reader.cancel();
return undefined;
}
chunks.push(value);
}
- const buffer = Buffer.concat(chunks);
- const base64 = buffer.toString("base64");
- return `data:${contentType.split(";")[0]};base64,${base64}`;
+ return { buffer: Buffer.concat(chunks), contentType };
} catch {
return undefined;
}
}
+function toDataUri(contentType: string, buffer: Buffer): string {
+ return `data:${contentType};base64,${buffer.toString("base64")}`;
+}
+
+/**
+ * Downloads a favicon and returns it as a base64 data URI.
+ * Returns undefined if the download fails or the image is too large.
+ */
+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);
+}
+
+/**
+ * Downloads the preview image, scales it down to {@link IMAGE_MAX_DIMENSION} and returns it as a
+ * base64 data URI, so the note carries the image itself instead of hotlinking the origin site (which
+ * would leak every reader's IP to it, and break whenever the remote URL rots).
+ *
+ * Transparency is preserved by re-encoding to PNG only when the image actually has non-opaque
+ * pixels; an opaque image becomes a JPEG, which is several times smaller — and this ends up inside
+ * the note's HTML, so every byte is synced and stored forever.
+ *
+ * Returns undefined when the image cannot be had at a reasonable size, in which case the preview is
+ * still shown without it — the title and description carry the value, not the picture.
+ */
+async function downloadImageAsDataUri(imageUrl: string): Promise<string | undefined> {
+ const downloaded = await downloadBinary(imageUrl, MAX_IMAGE_DOWNLOAD_SIZE, "image/jpeg");
+ if (!downloaded) return undefined;
+
+ const { buffer, contentType } = downloaded;
+ const isSmallEnoughToKeepVerbatim = buffer.byteLength <= MAX_VERBATIM_IMAGE_SIZE;
+
+ // An SVG scales natively, so it is kept as-is rather than rasterised (Jimp cannot read it anyway).
+ // The isSvg() sniff only runs on a buffer we would be willing to keep, to avoid stringifying megabytes.
+ if (contentType.includes("svg") || (isSmallEnoughToKeepVerbatim && isSvg(buffer.toString()))) {
+ return isSmallEnoughToKeepVerbatim ? toDataUri("image/svg+xml", buffer) : undefined;
+ }
+
+ try {
+ const image = await Jimp.read(buffer);
+
+ // Only ever scale down: scaleToFit() would happily enlarge a smaller image.
+ if (image.bitmap.width > IMAGE_MAX_DIMENSION || image.bitmap.height > IMAGE_MAX_DIMENSION) {
+ image.scaleToFit({ w: IMAGE_MAX_DIMENSION, h: IMAGE_MAX_DIMENSION });
+ }
+
+ // hasAlpha() inspects the pixels, not just the channel, so an opaque PNG still takes the
+ // JPEG path. An animated GIF/WebP collapses to its first frame, which is fine for a thumbnail.
+ return image.hasAlpha()
+ ? toDataUri("image/png", Buffer.from(await image.getBuffer("image/png")))
+ : toDataUri("image/jpeg", Buffer.from(await image.getBuffer("image/jpeg", { quality: IMAGE_JPEG_QUALITY })));
+ } 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.
+ getLog().info(`Could not decode link preview image ${imageUrl}: ${e}`);
+ return isSmallEnoughToKeepVerbatim && contentType.startsWith("image/")
+ ? toDataUri(contentType, buffer)
+ : undefined;
+ }
+}
+
/**
* Resolves a URL found in the page (`og:image` content, favicon `href`, …) against the page's own
* address, so a root-relative or relative one — both legal and common — becomes absolute. Without
@@ -114,7 +192,6 @@ async function resolveFavicon(document: ReturnType<typeof parse>, pageUrl: strin
async function fetchYouTubeMetadata(url: string, videoId: string): Promise<LinkEmbedMetadata> {
const metadata: LinkEmbedMetadata = {
url,
- image: `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`,
siteName: "YouTube",
embedType: "youtube"
};
@@ -122,6 +199,8 @@ async function fetchYouTubeMetadata(url: string, videoId: string): Promise<LinkE
// Download YouTube favicon as data URI
metadata.favicon = await downloadFaviconAsDataUri("https://www.youtube.com/favicon.ico");
+ let thumbnailUrl = `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`;
+
try {
const oembedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(url)}&format=json`;
const response = await safeFetch(oembedUrl);
@@ -131,11 +210,15 @@ async function fetchYouTubeMetadata(url: string, videoId: string): Promise<LinkE
const data = await response.json();
if (data.title) metadata.title = data.title;
if (data.author_name) metadata.description = data.author_name;
- if (data.thumbnail_url) metadata.image = data.thumbnail_url;
+ if (data.thumbnail_url) thumbnailUrl = data.thumbnail_url;
} catch {
metadata.title = "YouTube Video";
}
+ // The thumbnail is embedded like any other preview image: it is what Card display mode shows, and
+ // hotlinking it would tell YouTube every time the note is opened.
+ metadata.image = await downloadImageAsDataUri(thumbnailUrl);
+
return metadata;
}
@@ -169,10 +252,13 @@ async function fetchOpenGraphData(url: string) {
const favicon = await resolveFavicon(document, url);
+ const imageUrl = toAbsoluteUrl(getMeta("og:image"), url);
+ const image = imageUrl ? await downloadImageAsDataUri(imageUrl) : undefined;
+
return {
title: getMeta("og:title") || document.querySelector("title")?.textContent?.trim() || undefined,
description: getMeta("og:description") || getMeta("description") || undefined,
- image: toAbsoluteUrl(getMeta("og:image"), url),
+ image,
siteName: getMeta("og:site_name") || undefined,
favicon
};