Skip to content

Build your personal knowledge base with Trilium Notes

feat(images): handle ICO as an image rather than as an opaque file

Elian Doran501efc7f9498
diff --git a/apps/server/src/routes/api/sender.ts b/apps/server/src/routes/api/sender.ts
index d38f16f432..daa9132b5d 100644
--- a/apps/server/src/routes/api/sender.ts
+++ b/apps/server/src/routes/api/sender.ts
@@ -1,4 +1,4 @@
-import { note_service as noteService, special_notes as specialNotesService,utils } from "@triliumnext/core";
+import { ACCEPTED_IMAGE_MIMES, note_service as noteService, special_notes as specialNotesService,utils } from "@triliumnext/core";
import type { Request } from "express";
import imageType from "image-type";
@@ -14,7 +14,7 @@ async function uploadImage(req: Request) {
};
}
- if (!["image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"].includes(file.mimetype)) {
+ if (!ACCEPTED_IMAGE_MIMES.has(file.mimetype)) {
return [400, `Unknown image type: ${file.mimetype}`];
}
if (typeof file.buffer === "string") {
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index fab709fea1..e8708f0553 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -114,7 +114,7 @@ export { default as imageInfoService } from "./services/image_info";
export { estimateJpegQuality } from "./services/jpeg_quality";
export { inspectImage, type InspectedImage, UNKNOWN_FORMAT } from "./services/image_inspect";
export { type CoreConfig, initConfig, getConfig } from "./services/config";
-export { default as imageService } from "./services/image";
+export { ACCEPTED_IMAGE_MIMES, default as imageService } from "./services/image";
export { t } from "i18next";
export type { RequestProvider, ExecOpts, CookieJar } from "./services/request";
export type * from "./meta";
diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.ts
index 9cff4e87af..9a227502d7 100644
--- a/packages/trilium-core/src/routes/api/attachments.spec.ts
+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts
@@ -43,6 +43,31 @@ async function saveAttachment(
return attachment as AttachmentPojo;
}
+/** A 1x1 transparent PNG, small enough to be written out in full. */
+const PIXEL_PNG = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC",
+ "base64"
+);
+
+/**
+ * Wraps a picture in an icon directory of one entry, which is what an `.ico` is: a container of
+ * several sizes rather than an image format of its own. Built here rather than fixtured so the
+ * bytes that make it an icon — the type, and the offset the picture starts at — stay readable.
+ */
+function icoWrapping(image: Buffer): Buffer {
+ const directory = Buffer.alloc(22);
+ directory.writeUInt16LE(1, 2); // type: icon, as opposed to a cursor
+ directory.writeUInt16LE(1, 4); // one entry
+ directory.writeUInt8(1, 6); // width
+ directory.writeUInt8(1, 7); // height
+ directory.writeUInt16LE(1, 10); // colour planes
+ directory.writeUInt16LE(32, 12); // bits per pixel
+ directory.writeUInt32LE(image.length, 14);
+ directory.writeUInt32LE(directory.length, 18); // the picture starts where the directory ends
+
+ return Buffer.concat([ directory, image ]);
+}
+
function attachmentIsDeleted(attachmentId: string): number | null {
const row = getSql().getRowOrNull<{ isDeleted: number }>(
"SELECT isDeleted FROM attachments WHERE attachmentId = ?",
@@ -182,6 +207,35 @@ describe("Attachments API (core)", () => {
expect((fetched.body as Uint8Array).length).toBeGreaterThan(0);
});
+ it("uploads an ICO as an image rather than as a file", async () => {
+ const { noteId } = await createTextNote(api, { title: "Icon upload target" });
+
+ const res = await api.post<{ uploaded: boolean; url: string }>(
+ `/api/notes/${noteId}/attachments/upload`,
+ {
+ file: {
+ originalname: "site.ico",
+ mimetype: "image/x-icon",
+ buffer: icoWrapping(PIXEL_PNG)
+ }
+ }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.uploaded).toBe(true);
+ // A file attachment would answer with a `#root/...?viewMode=attachments` link instead,
+ // which is not something an <img> can be pointed at — the whole reason a favicon has to
+ // arrive here as an image.
+ expect(res.body.url).toContain("/image/");
+
+ const fetched = await api.get(`/${res.body.url}`);
+ expect(fetched.status).toBe(200);
+
+ // Stored under the registered type, not the `image/ico` that `image/<ext>` would give,
+ // since that is what the image route serves it as.
+ const [ attachment ] = (await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body;
+ expect(attachment).toMatchObject({ role: "image", mime: "image/x-icon" });
+ });
+
it("reports a missing upload when no file is present", async () => {
const { noteId } = await createTextNote(api, { title: "No file target" });
diff --git a/packages/trilium-core/src/routes/api/attachments.ts b/packages/trilium-core/src/routes/api/attachments.ts
index f2808d94d8..c53311fc8e 100644
--- a/packages/trilium-core/src/routes/api/attachments.ts
+++ b/packages/trilium-core/src/routes/api/attachments.ts
@@ -7,7 +7,7 @@ type FileRequest<P> = Omit<Request<P>, "file"> & { file?: File };
import becca from "../../becca/becca.js";
import blobService from "../../services/blob.js";
-import imageService from "../../services/image.js";
+import imageService, { ACCEPTED_IMAGE_MIMES } from "../../services/image.js";
import { wrapStringOrBuffer } from "../../services/utils/binary.js";
function getAttachmentBlob(req: Request<{ attachmentId: string }>) {
@@ -64,7 +64,7 @@ async function uploadAttachment(req: FileRequest<{ noteId: string }>) {
// Convert buffer to Uint8Array (Buffer extends Uint8Array, string needs encoding)
const buffer = wrapStringOrBuffer(file.buffer as string | Uint8Array);
- if (["image/png", "image/jpg", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"].includes(file.mimetype)) {
+ if (ACCEPTED_IMAGE_MIMES.has(file.mimetype)) {
const attachment = imageService.saveImageToAttachment(noteId, buffer, file.originalname, true, true);
// The URL below is fetched the moment this answers — the editor puts it straight into the
diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.ts
index 75f877c36c..96b6e7b3f4 100644
--- a/packages/trilium-core/src/routes/api/image.ts
+++ b/packages/trilium-core/src/routes/api/image.ts
@@ -8,7 +8,7 @@ import becca from "../../becca/becca.js";
import type BNote from "../../becca/entities/bnote.js";
import type BRevision from "../../becca/entities/brevision.js";
import { ValidationError } from "../../errors.js";
-import imageService from "../../services/image.js";
+import imageService, { ACCEPTED_IMAGE_MIMES } from "../../services/image.js";
import imageCompressionService from "../../services/image_compression.js";
import imageInfoService from "../../services/image_info.js";
import imageInventoryService from "../../services/image_inventory.js";
@@ -124,7 +124,7 @@ async function updateImage(req: FileRequest<{ noteId: string }>) {
};
}
- if (!["image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"].includes(file.mimetype)) {
+ if (!ACCEPTED_IMAGE_MIMES.has(file.mimetype)) {
return {
uploaded: false,
message: `Unknown image type: ${file.mimetype}`
diff --git a/packages/trilium-core/src/services/image.ts b/packages/trilium-core/src/services/image.ts
index f9a910f774..a4ecc54954 100644
--- a/packages/trilium-core/src/services/image.ts
+++ b/packages/trilium-core/src/services/image.ts
@@ -14,9 +14,40 @@ import protectedSessionService from "./protected_session.js";
import { getSql } from "./sql/index.js";
import { sanitizeHtml } from "./sanitizer.js";
+/**
+ * The media types an upload is handled as an image under — stored as an image note or as an
+ * `image`-role attachment, rather than as an opaque file with only a download link to it.
+ *
+ * ICO is included because a favicon is one, and treating it as a file made an `.ico` dropped into a
+ * note produce a download link instead of a picture. Nothing downstream has to learn the format:
+ * `image-type` identifies it from its magic number, and the compression planner skips it as an
+ * unsupported format, so it is simply stored as it arrived. Both spellings are listed —
+ * `image/vnd.microsoft.icon` is the registered name, `image/x-icon` is what servers actually send.
+ *
+ * `image/jpg` is likewise unregistered, but some clients send it for a JPEG.
+ */
+export const ACCEPTED_IMAGE_MIMES = new Set([
+ "image/png",
+ "image/jpg",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+ "image/svg+xml",
+ "image/x-icon",
+ "image/vnd.microsoft.icon"
+]);
+
+/** Extensions whose media type is not simply `image/<ext>`. */
+const IMAGE_MIME_EXCEPTIONS: Record<string, string> = {
+ svg: "image/svg+xml",
+ // There is no `image/ico`: serving one under it leaves the picture to the browser's sniffing
+ // rather than to the type it was told.
+ ico: "image/x-icon"
+};
+
function getImageMimeFromExtension(ext: string): string {
ext = ext.toLowerCase();
- return `image/${ext === "svg" ? "svg+xml" : ext}`;
+ return IMAGE_MIME_EXCEPTIONS[ext] ?? `image/${ext}`;
}
/**
diff --git a/packages/trilium-core/src/services/image_inspect.spec.ts b/packages/trilium-core/src/services/image_inspect.spec.ts
index 73f8a6e832..1ee27b9b83 100644
--- a/packages/trilium-core/src/services/image_inspect.spec.ts
+++ b/packages/trilium-core/src/services/image_inspect.spec.ts
@@ -42,6 +42,11 @@ function uint32(value: number): number[] {
return [ (value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff ];
}
+/** An icon directory stating one entry of the given size, each edge a single byte. */
+function ico(width: number, height: number): Uint8Array {
+ return bytes(0x00, 0x00, 0x01, 0x00, 0x01, 0x00, width & 0xff, height & 0xff);
+}
+
function bytes(...values: number[]): Uint8Array {
// Padded past the length below which nothing is read at all.
return Uint8Array.from([ ...values, ...new Array(Math.max(0, 16 - values.length)).fill(0) ]);
@@ -59,6 +64,13 @@ describe("inspectImage", () => {
.toMatchObject({ format: "webp", mime: "image/webp" });
expect(inspectImage(text("<svg xmlns='http://www.w3.org/2000/svg'></svg>")))
.toMatchObject({ format: "svg", mime: "image/svg+xml" });
+ expect(inspectImage(ico(16, 16))).toMatchObject({ format: "ico", mime: "image/x-icon" });
+ });
+
+ it("does not read a cursor as an icon", () => {
+ // Same directory layout, type 2 rather than 1 — not something a note holds, and reporting
+ // it as an icon would have it served as one.
+ expect(inspectImage(bytes(0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x20, 0x20)).format).toBe(UNKNOWN_FORMAT);
});
it("recognises an SVG behind an XML declaration", () => {
@@ -126,6 +138,12 @@ describe("inspectImage", () => {
expect(inspectImage(bmp)).toMatchObject({ format: "bmp", width: 640, height: 480 });
});
+ it("reads an ICO from its first directory entry, where 0 means 256", () => {
+ expect(inspectImage(ico(48, 32))).toMatchObject({ width: 48, height: 32 });
+ // A single byte per edge cannot hold 256, so the format spends 0 on it.
+ expect(inspectImage(ico(0, 0))).toMatchObject({ width: 256, height: 256 });
+ });
+
it("measures nothing for a format whose header it does not read", () => {
const webp = bytes(0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50);
diff --git a/packages/trilium-core/src/services/image_inspect.ts b/packages/trilium-core/src/services/image_inspect.ts
index 98e848c2c2..ff1dd8a284 100644
--- a/packages/trilium-core/src/services/image_inspect.ts
+++ b/packages/trilium-core/src/services/image_inspect.ts
@@ -12,7 +12,7 @@
* standing in for a measurement that was not taken.
*/
export interface InspectedImage {
- /** "jpg", "png", "gif", "webp", "bmp", "svg", or {@link UNKNOWN_FORMAT}. */
+ /** "jpg", "png", "gif", "webp", "bmp", "svg", "ico", or {@link UNKNOWN_FORMAT}. */
format: string;
mime: string;
width: number | null;
@@ -56,6 +56,7 @@ function readHeader(format: string, buffer: Uint8Array): Partial<ImageMeasuremen
// needs a walk through palette and header variants that nothing here has a use for.
case "gif": return readUint16LePair(buffer, 6, 8);
case "bmp": return buffer.length >= 26 ? readUint32LePair(buffer, 18, 22) : {};
+ case "ico": return readIcoHeader(buffer);
default: return {};
}
}
@@ -89,9 +90,32 @@ function detectFormat(buffer: Uint8Array): string {
return "webp";
}
+ // An icon directory: two reserved zero bytes, then the type as a little-endian 1. Type 2 is a
+ // cursor, which shares the layout but is not something a note holds.
+ if (startsWith(buffer, [ 0x00, 0x00, 0x01, 0x00 ])) {
+ return "ico";
+ }
+
return startsWith(buffer, [ 0x42, 0x4d ]) ? "bmp" : UNKNOWN_FORMAT;
}
+/**
+ * An ICO is a directory of images at different sizes rather than a single picture. Its first entry
+ * is the one reported, that being what a renderer handed the whole file sizes from.
+ *
+ * Each edge is a single byte, and 0 means 256 — how the format fits its largest size into a byte.
+ */
+function readIcoHeader(buffer: Uint8Array): Partial<ImageMeasurements> {
+ if (buffer.length < 8) {
+ return {};
+ }
+
+ return {
+ width: buffer[6] || 256,
+ height: buffer[7] || 256
+ };
+}
+
/**
* The IHDR chunk is required to come first, so everything a PNG states about itself sits at a fixed
* offset: size, then bits per channel, then the colour type the channels follow from.
@@ -239,5 +263,6 @@ const FORMAT_MIMES: Record<string, string> = {
webp: "image/webp",
bmp: "image/bmp",
svg: "image/svg+xml",
+ ico: "image/x-icon",
[UNKNOWN_FORMAT]: "application/octet-stream"
};