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): keep the size of an icon a preview draws, instead of losing the icon
Elian Doranafe6f65f0380
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.tsindex ba348fbb28..0f4cfd3348 100644--- a/apps/server/src/routes/api/link_embed.spec.ts+++ b/apps/server/src/routes/api/link_embed.spec.ts@@ -94,6 +94,31 @@ function makeIco(): Buffer {return Buffer.concat([ directory, Buffer.from([ 0, 0, 0, 0 ]) ]);}+/**+ * An icon directory of several sizes, the shape a real site's icon takes — Trilium's own carries+ * six, of which only the smallest is ever drawn.+ */+function makeMultiSizeIco(sizes: { edge: number; bytes: number }[]): Buffer {+ const directory = Buffer.alloc(6 + sizes.length * 16);+ directory.writeUInt16LE(1, 2);+ directory.writeUInt16LE(sizes.length, 4);++ const payloads: Buffer[] = [];+ let offset = directory.length;++ for (const [ index, { edge, bytes } ] of sizes.entries()) {+ const at = 6 + index * 16;+ directory.writeUInt8(edge % 256, at); // 256 is written as 0+ directory.writeUInt8(edge % 256, at + 1);+ directory.writeUInt32LE(bytes, at + 8);+ directory.writeUInt32LE(offset, at + 12);+ payloads.push(Buffer.alloc(bytes, edge));+ offset += bytes;+ }++ return Buffer.concat([ directory, ...payloads ]);+}+describe("extractYouTubeVideoId", () => {it("extracts ids and rejects non-YouTube URLs", () => {expect(extractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");@@ -451,6 +476,48 @@ describe("link-embed getMetadata", () => {expect(result.favicon).toBeUndefined();});+ it("keeps only the size of an icon a preview draws, so a large one is not lost to the ceiling", async () => {+ // The shape that made triliumnotes.org show no icon at all: 114KB across six sizes, of+ // which the rendered entry is 1.1KB. Fetched whole and stored trimmed, because the sizes+ // are what the choice is made from — enforcing the ceiling on the download instead simply+ // threw the icon away.+ const html = `<html><head><title>Plain</title><link rel="icon" href="/fav.ico"></head></html>`;+ const fat = makeMultiSizeIco([+ { edge: 16, bytes: 1128 },+ { edge: 32, bytes: 4264 },+ { edge: 128, bytes: 67624 },+ { edge: 256, bytes: 14550 }+ ]);+ expect(fat.byteLength).toBeGreaterThan(64 * 1024);++ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("fav.ico")) return fakeResponse(fat, { contentType: "image/vnd.microsoft.icon" });+ return fakeResponse(html, { contentType: "text/html" });+ });++ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));++ expect(result.favicon).toBeTruthy();+ expect(stored("favicon")?.fileName).toBe("example.com.ico");+ // The 16x16 entry, and a one-entry directory to hold it.+ expect(stored("favicon")?.buffer.byteLength).toBe(22 + 1128);+ });++ it("drops an icon that is one picture too large to keep, having nothing to give up", async () => {+ const html = `<html><head><title>Plain</title><link rel="icon" href="/fav.ico"></head></html>`;+ const huge = makeMultiSizeIco([ { edge: 256, bytes: 100 * 1024 } ]);++ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("fav.ico")) return fakeResponse(huge, { contentType: "image/x-icon" });+ return fakeResponse(html, { contentType: "text/html" });+ });++ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));++ expect(result.favicon).toBeUndefined();+ expect(stored("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>`;diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.tsindex 8702cf2e4f..377f13a071 100644--- a/apps/server/src/routes/api/link_embed.ts+++ b/apps/server/src/routes/api/link_embed.ts@@ -12,10 +12,22 @@ import isSvg from "is-svg";import { Jimp } from "jimp";import { parse } from "node-html-parser";+import { trimIcoToSmallestEntry } from "../../services/ico.js";import { getImageTypeFromBuffer } from "../../services/image_codec.js";import { safeFetch, validateUrl } from "../../services/safe_fetch.js";const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB++/**+ * How much of a favicon to fetch.+ *+ * Deliberately far above what is kept. A site's icon is often a directory of several pictures where+ * only the smallest is ever drawn — Trilium's own is 114KB, of which the rendered entry is 1.1KB —+ * and the whole file has to arrive before the rest can be dropped. Enforcing the storage ceiling+ * here instead is what left such a site with no icon at all.+ */+const MAX_FAVICON_DOWNLOAD_SIZE = 256 * 1024; // 256KB+/** How large a favicon may be once trimmed. Icons that are one picture already measure a few KB. */const MAX_FAVICON_SIZE = 64 * 1024; // 64KB/** Longest edge of the preview image kept in the note; larger images are scaled down to fit. */@@ -194,13 +206,23 @@ async function asPicture(buffer: Buffer): Promise<DownloadedPicture | undefined>}/**- * Downloads a favicon.- * Returns undefined if the download fails, the image is too large, or it is not an image.+ * Downloads a favicon, keeping only the size of it a preview will draw.+ * Returns undefined if the download fails, it is not an image, or too much of it is left.*/async function downloadFavicon(faviconUrl: string): Promise<DownloadedPicture | undefined> {- const downloaded = await downloadBinary(faviconUrl, MAX_FAVICON_SIZE, "image/x-icon");+ const downloaded = await downloadBinary(faviconUrl, MAX_FAVICON_DOWNLOAD_SIZE, "image/x-icon");++ if (!downloaded) {+ return undefined;+ }++ // An icon directory gives up the sizes nothing will look at; anything else is kept as it came.+ const trimmed = trimIcoToSmallestEntry(downloaded.buffer);+ const bytes = trimmed ? Buffer.from(trimmed) : downloaded.buffer;- return downloaded ? await asPicture(downloaded.buffer) : undefined;+ // The ceiling is on what is kept, not on what arrived: a file that is one large picture has+ // nothing to give up, and is the case this refuses.+ return bytes.byteLength <= MAX_FAVICON_SIZE ? await asPicture(bytes) : undefined;}/**diff --git a/apps/server/src/services/ico.spec.ts b/apps/server/src/services/ico.spec.tsnew file mode 100644index 0000000000..af542d73e7--- /dev/null+++ b/apps/server/src/services/ico.spec.ts@@ -0,0 +1,171 @@+import { describe, expect, it } from "vitest";++import { trimIcoToSmallestEntry } from "./ico.js";++interface FakeEntry {+ edge: number;+ payload: Uint8Array;+}++/** Bytes that stand in for a picture, distinct per entry so the right one can be recognised. */+function payload(marker: number, length = 8): Uint8Array {+ return Uint8Array.from({ length }, () => marker);+}++/** The signature a PNG-carrying entry opens with, the larger sizes in a real icon using that form. */+const PNG_SIGNATURE = Uint8Array.from([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ]);++/** Builds an icon file holding the given pictures, laid out the way a real one is. */+function buildIco(entries: FakeEntry[], { type = 1 } = {}): Uint8Array {+ const directorySize = 6 + entries.length * 16;+ const bytes = new Uint8Array(directorySize + entries.reduce((sum, e) => sum + e.payload.byteLength, 0));+ const view = new DataView(bytes.buffer);++ view.setUint16(2, type, true);+ view.setUint16(4, entries.length, true);++ let offset = directorySize;++ for (const [ index, entry ] of entries.entries()) {+ const at = 6 + index * 16;++ // One byte per edge; 256 is written as 0, which is the whole reason it wraps.+ bytes[at] = entry.edge % 256;+ bytes[at + 1] = entry.edge % 256;+ view.setUint16(at + 4, 1, true); // colour planes+ view.setUint16(at + 6, 32, true); // bits per pixel+ view.setUint32(at + 8, entry.payload.byteLength, true);+ view.setUint32(at + 12, offset, true);+ bytes.set(entry.payload, offset);+ offset += entry.payload.byteLength;+ }++ return bytes;+}++/** Reads back what a trimmed file says it holds. */+function readTrimmed(bytes: Uint8Array) {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);++ return {+ count: view.getUint16(4, true),+ edge: bytes[6] || 256,+ pictureAt: view.getUint32(6 + 12, true),+ picture: bytes.subarray(22)+ };+}++describe("trimIcoToSmallestEntry", () => {+ it("keeps the smallest picture worth drawing and drops the rest", () => {+ // The shape a site's icon actually takes — Trilium's own carries these six sizes, of which+ // a preview draws the first and stores all of them.+ const original = buildIco([+ { edge: 16, payload: payload(0x11) },+ { edge: 32, payload: payload(0x22, 64) },+ { edge: 48, payload: payload(0x33, 128) },+ { edge: 64, payload: payload(0x44, 256) },+ { edge: 128, payload: payload(0x55, 512) },+ { edge: 256, payload: payload(0x66, 1024) }+ ]);++ const trimmed = trimIcoToSmallestEntry(original);+ expect(trimmed).not.toBeNull();++ const result = readTrimmed(trimmed ?? new Uint8Array());+ expect(result.count).toBe(1);+ expect(result.edge).toBe(16);+ expect(result.picture).toStrictEqual(payload(0x11));+ // The picture now starts directly after the one entry that is left.+ expect(result.pictureAt).toBe(22);+ expect(trimmed?.byteLength).toBeLessThan(original.byteLength / 10);+ });++ it("copies the picture across untouched, whichever form it is in", () => {+ // Nothing is decoded, so the older BMP form and the PNG form used for larger sizes are+ // handled by the same code — which is what makes this cheap enough to be worth doing.+ const png = new Uint8Array([ ...PNG_SIGNATURE, 1, 2, 3 ]);+ const trimmed = trimIcoToSmallestEntry(buildIco([+ { edge: 256, payload: png },+ { edge: 16, payload: payload(0xab, 12) }+ ]));++ expect(readTrimmed(trimmed ?? new Uint8Array()).picture).toStrictEqual(payload(0xab, 12));++ // And the same file read with a floor no entry but the PNG one clears.+ const keptPng = trimIcoToSmallestEntry(buildIco([+ { edge: 256, payload: png },+ { edge: 16, payload: payload(0xab, 12) }+ ]), 32);++ expect(readTrimmed(keptPng ?? new Uint8Array()).picture).toStrictEqual(png);+ });++ it("reads an edge of 0 as 256 rather than as nothing", () => {+ // Written as 0 because a byte cannot hold 256. Read literally it would look like the+ // smallest picture in the file instead of the largest.+ const trimmed = trimIcoToSmallestEntry(buildIco([+ { edge: 256, payload: payload(0xaa) },+ { edge: 8, payload: payload(0xbb) }+ ]));++ // 8 is below the floor, so the 256 is the only one usable — which it would not be if its+ // edge had been read as 0.+ expect(readTrimmed(trimmed ?? new Uint8Array()).picture).toStrictEqual(payload(0xaa));+ });++ it("settles for the largest when every picture is below the floor", () => {+ const trimmed = trimIcoToSmallestEntry(buildIco([+ { edge: 8, payload: payload(0xcc) },+ { edge: 12, payload: payload(0xdd) }+ ]));++ expect(readTrimmed(trimmed ?? new Uint8Array()).edge).toBe(12);+ expect(readTrimmed(trimmed ?? new Uint8Array()).picture).toStrictEqual(payload(0xdd));+ });++ it("answers nothing when the file is one picture already", () => {+ // Not a failure — there is simply nothing to drop, and the caller keeps what it had.+ expect(trimIcoToSmallestEntry(buildIco([ { edge: 32, payload: payload(0x01) } ]))).toBeNull();+ });++ it("answers nothing for bytes that are not an icon directory", () => {+ expect(trimIcoToSmallestEntry(PNG_SIGNATURE)).toBeNull();+ expect(trimIcoToSmallestEntry(new Uint8Array())).toBeNull();+ expect(trimIcoToSmallestEntry(new Uint8Array([ 0, 0, 1 ]))).toBeNull();+ // A cursor shares the layout but is not a picture a note holds.+ expect(trimIcoToSmallestEntry(buildIco([+ { edge: 16, payload: payload(1) },+ { edge: 32, payload: payload(2) }+ ], { type: 2 }))).toBeNull();+ });++ it("refuses a directory it cannot read in full, rather than reading past the end", () => {+ // These bytes are whatever a linked site served, so a length or offset that does not fit+ // the file has to answer nothing instead of reaching outside it.+ const claimsMoreEntriesThanFit = new Uint8Array(6 + 16);+ new DataView(claimsMoreEntriesThanFit.buffer).setUint16(2, 1, true);+ new DataView(claimsMoreEntriesThanFit.buffer).setUint16(4, 5, true);+ expect(trimIcoToSmallestEntry(claimsMoreEntriesThanFit)).toBeNull();++ const runsPastTheEnd = buildIco([+ { edge: 16, payload: payload(1) },+ { edge: 32, payload: payload(2) }+ ]);+ new DataView(runsPastTheEnd.buffer).setUint32(6 + 8, 0xffff, true);+ expect(trimIcoToSmallestEntry(runsPastTheEnd)).toBeNull();++ const startsInsideTheDirectory = buildIco([+ { edge: 16, payload: payload(1) },+ { edge: 32, payload: payload(2) }+ ]);+ new DataView(startsInsideTheDirectory.buffer).setUint32(6 + 12, 2, true);+ expect(trimIcoToSmallestEntry(startsInsideTheDirectory)).toBeNull();++ const holdsNothing = buildIco([+ { edge: 16, payload: payload(1) },+ { edge: 32, payload: payload(2) }+ ]);+ new DataView(holdsNothing.buffer).setUint32(6 + 8, 0, true);+ expect(trimIcoToSmallestEntry(holdsNothing)).toBeNull();+ });+});diff --git a/apps/server/src/services/ico.ts b/apps/server/src/services/ico.tsnew file mode 100644index 0000000000..218d46e183--- /dev/null+++ b/apps/server/src/services/ico.ts@@ -0,0 +1,113 @@+/**+ * Dropping the pictures an `.ico` carries that nobody is going to look at.+ *+ * An icon file is a directory of independent pictures at different sizes, and a site's icon+ * routinely holds five or six of them, up to 256x256, where a link preview draws exactly one at 16+ * pixels. Trilium's own site ships 114KB of icon, of which the entry actually rendered is 1.1KB.+ * Left whole, such a file is not merely wasteful — it is over the ceiling a favicon is allowed, so+ * the site ends up with no icon at all rather than a large one.+ *+ * Nothing here decodes anything. The chosen picture's bytes are copied across untouched, which is+ * what lets one piece of code handle both kinds of entry an icon may hold: the older BMP form and+ * the PNG form used for the larger sizes. Lifting an entry out into a file of its own would mean+ * telling them apart and, for the BMP form, rebuilding a header from the DIB — including the+ * doubled height and the one-bit transparency mask that ICO uses in place of an alpha channel.+ */++/** Reserved bytes, type, and the number of pictures that follow. */+const DIRECTORY_HEADER_SIZE = 6;+/** Size, colour depth, and where in the file the picture is. */+const DIRECTORY_ENTRY_SIZE = 16;+/** Type 1 is an icon. Type 2 is a cursor, which shares the layout but is not a picture for a note. */+const ICON_TYPE = 1;+/** Below this an icon is too small to draw a preview with, whatever else the file offers. */+const DEFAULT_MIN_EDGE = 16;++interface IconDirectoryEntry {+ /** Longest edge in pixels. */+ edge: number;+ offset: number;+ length: number;+ /** The entry's own 16 bytes, carried over as they are apart from the offset. */+ header: Uint8Array;+}++/**+ * An icon file holding only the smallest picture still worth drawing, or null when there is nothing+ * to gain — a single picture already, or bytes that cannot be read as an icon directory at all.+ * The caller keeps what it had in that case.+ *+ * These bytes are whatever a linked site chose to serve, so every field is bounds-checked rather+ * than trusted: a length or offset pointing past the end of the file answers null instead of+ * reading somewhere it should not.+ */+export function trimIcoToSmallestEntry(bytes: Uint8Array, minEdge = DEFAULT_MIN_EDGE): Uint8Array | null {+ const entries = readIconDirectory(bytes);++ if (!entries || entries.length < 2) {+ return null;+ }++ // The smallest that is still big enough. Where every picture in the file is below the floor,+ // the largest of them is the best on offer.+ const usable = entries.filter((entry) => entry.edge >= minEdge).sort((a, b) => a.edge - b.edge);+ const kept = usable[0] ?? entries.reduce((largest, entry) => (entry.edge > largest.edge ? entry : largest));++ const pictureAt = DIRECTORY_HEADER_SIZE + DIRECTORY_ENTRY_SIZE;+ const trimmed = new Uint8Array(pictureAt + kept.length);+ const directory = new DataView(trimmed.buffer);++ directory.setUint16(2, ICON_TYPE, true);+ directory.setUint16(4, 1, true);+ trimmed.set(kept.header, DIRECTORY_HEADER_SIZE);+ // Everything about the picture is unchanged except where it now begins: directly after the one+ // entry that is left, rather than after the several there were.+ directory.setUint32(DIRECTORY_HEADER_SIZE + 12, pictureAt, true);+ trimmed.set(bytes.subarray(kept.offset, kept.offset + kept.length), pictureAt);++ return trimmed;+}++/** The pictures an icon file says it holds, or null if it does not read as one. */+function readIconDirectory(bytes: Uint8Array): IconDirectoryEntry[] | null {+ if (bytes.byteLength < DIRECTORY_HEADER_SIZE) {+ return null;+ }++ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);++ if (view.getUint16(0, true) !== 0 || view.getUint16(2, true) !== ICON_TYPE) {+ return null;+ }++ const count = view.getUint16(4, true);++ if (count < 1 || bytes.byteLength < DIRECTORY_HEADER_SIZE + count * DIRECTORY_ENTRY_SIZE) {+ return null;+ }++ const entries: IconDirectoryEntry[] = [];++ for (let index = 0; index < count; index++) {+ const at = DIRECTORY_HEADER_SIZE + index * DIRECTORY_ENTRY_SIZE;+ const length = view.getUint32(at + 8, true);+ const offset = view.getUint32(at + 12, true);++ // A picture holding nothing, starting inside the directory, or running past the end of the+ // file. One malformed entry condemns the file: the sizes are what the choice is made from,+ // so a directory that cannot be read in full cannot be chosen from either.+ if (length < 1 || offset < DIRECTORY_HEADER_SIZE || offset + length > bytes.byteLength) {+ return null;+ }++ entries.push({+ // One byte per edge, where 0 means 256 — how the format fits its largest size into a byte.+ edge: Math.max(view.getUint8(at) || 256, view.getUint8(at + 1) || 256),+ offset,+ length,+ header: bytes.subarray(at, at + DIRECTORY_ENTRY_SIZE)+ });+ }++ return entries;+}