Skip to content

Build your personal knowledge base with Trilium Notes

refactor(images): decide what counts as a picture in one place

Elian Doran130a1c0585c3
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index ccbd059fd2..12904e621e 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -1,4 +1,4 @@
-import { DISPLAYABLE_LOCALE_IDS, LOCALES } from "@triliumnext/commons";
+import { DISPLAYABLE_LOCALE_IDS, IMAGE_MIMES, LOCALES } from "@triliumnext/commons";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import imageService from "../../../services/image.js";
@@ -163,24 +163,23 @@ describe("CK config", () => {
// The `text-editor.ck` section of the English catalog is the registry of editor strings: each
// entry names the English message id a plugin passes to `editor.t()`, and the value the editor
// gets for it is that key resolved through the app's i18n.
- it("claims every media type the upload endpoint stores as an image", async () => {
+ it("claims exactly the media types the upload endpoint stores as images", async () => {
const config = await buildConfig(baseOpts());
const types = (config.image as { upload: { types: string[] } }).upload.types;
- // The editor decides whether a dropped file is an image with this exact expression (see
+ // The editor decides whether a dropped file is a picture with this exact expression (see
// createImageTypeRegExp) — anchored, so a subtype has to be listed in full.
const claimed = new RegExp(`^image\\/(${types.map((type) => type.replace("+", "\\+")).join("|")})$`);
- // Kept in step with ACCEPTED_IMAGE_MIMES in trilium-core's image service. A type the server
- // stores as an image but the editor does not claim falls through to the file-upload plugin,
- // which builds a reference link out of it — and a reference link cannot be pointed at the
- // `api/attachments/.../image/...` URL the server answers with, so it renders as
- // "[missing note]" rather than as the picture.
- for (const mime of [
- "image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml",
- "image/x-icon", "image/vnd.microsoft.icon"
- ]) {
+ for (const mime of IMAGE_MIMES) {
expect(claimed.test(mime), mime).toBe(true);
}
+
+ // And nothing beyond them. A type the editor claims but the endpoint does not store as an
+ // image is the worse half of the mismatch: the editor inserts a picture, the endpoint
+ // answers with a `#root/...` file reference, and that goes into the <img src> unexamined.
+ expect(types.length).toBe(IMAGE_MIMES.length);
+ // TIFF is the one deliberately left out — no browser but Safari draws one in an <img>.
+ expect(claimed.test("image/tiff")).toBe(false);
});
it("turns the English editor catalog into the dictionary the editor resolves messages through", async () => {
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 3c315e6b81..1671f803bb 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -1,6 +1,6 @@
import { type EditorConfig, getCkLocale, SnippetDefinition } from "@triliumnext/ckeditor5";
import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";
-import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
+import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
import i18next from "i18next";
import { copyTextWithToast } from "../../../services/clipboard_ext.js";
@@ -111,18 +111,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
"toggleImageCaption"
],
upload: {
- // Matched against a dropped file's media type as `^image/(<one of these>)$`, which
- // is what decides whether the editor inserts a picture or hands the file to the
- // file-upload plugin to make a reference link out of. So this has to claim
- // everything the upload endpoint stores as an image (ACCEPTED_IMAGE_MIMES): a type
- // the server calls an image but the editor calls a file ends up as a reference link
- // pointed at an `api/attachments/.../image/...` URL, which is not a note URL and so
- // renders as "[missing note]". Both ICO spellings are listed for the same reason
- // the server accepts both — servers send either.
- types: [
- "jpeg", "png", "gif", "bmp", "webp", "tiff", "svg", "svg+xml", "avif",
- "x-icon", "vnd.microsoft.icon"
- ]
+ // Derived rather than listed, so what the editor inserts as a picture and what the
+ // upload endpoint stores as one cannot drift apart — either direction of a mismatch
+ // is a broken element. See IMAGE_MIMES.
+ types: [ ...IMAGE_UPLOAD_SUBTYPES ]
}
},
heading: {
diff --git a/apps/server/src/routes/api/sender.ts b/apps/server/src/routes/api/sender.ts
index daa9132b5d..17379529ab 100644
--- a/apps/server/src/routes/api/sender.ts
+++ b/apps/server/src/routes/api/sender.ts
@@ -1,4 +1,5 @@
-import { ACCEPTED_IMAGE_MIMES, note_service as noteService, special_notes as specialNotesService,utils } from "@triliumnext/core";
+import { isAcceptedImageMime } from "@triliumnext/commons";
+import { note_service as noteService, special_notes as specialNotesService,utils } from "@triliumnext/core";
import type { Request } from "express";
import imageType from "image-type";
@@ -14,7 +15,7 @@ async function uploadImage(req: Request) {
};
}
- if (!ACCEPTED_IMAGE_MIMES.has(file.mimetype)) {
+ if (!isAcceptedImageMime(file.mimetype)) {
return [400, `Unknown image type: ${file.mimetype}`];
}
if (typeof file.buffer === "string") {
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts
index 9fed267658..f9dd59974e 100644
--- a/packages/commons/src/index.ts
+++ b/packages/commons/src/index.ts
@@ -5,6 +5,7 @@ export * from "./lib/keyboard_actions_interface.js";
export * from "./lib/hidden_subtree.js";
export * from "./lib/rows.js";
export * from "./lib/test-utils.js";
+export * from "./lib/image_mimes.js";
export * from "./lib/mime_type.js";
export * from "./lib/office.js";
export * from "./lib/bulk_actions.js";
diff --git a/packages/commons/src/lib/image_mimes.spec.ts b/packages/commons/src/lib/image_mimes.spec.ts
new file mode 100644
index 0000000000..487185d6dc
--- /dev/null
+++ b/packages/commons/src/lib/image_mimes.spec.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from "vitest";
+
+import { IMAGE_MIMES, IMAGE_UPLOAD_SUBTYPES, isAcceptedImageMime } from "./image_mimes.js";
+
+describe("isAcceptedImageMime", () => {
+ it("accepts every listed type and nothing else", () => {
+ for (const mime of IMAGE_MIMES) {
+ expect(isAcceptedImageMime(mime), mime).toBe(true);
+ }
+
+ // TIFF is deliberately absent: an <img> cannot draw one outside Safari, so it is stored as
+ // a file and gets a working reference link rather than a picture that never appears.
+ for (const mime of [ "image/tiff", "application/pdf", "text/plain", "image/", "png" ]) {
+ expect(isAcceptedImageMime(mime), mime).toBe(false);
+ }
+
+ expect(isAcceptedImageMime(undefined)).toBe(false);
+ expect(isAcceptedImageMime(null)).toBe(false);
+ expect(isAcceptedImageMime("")).toBe(false);
+ });
+
+ it("recognises both spellings of an icon, and both of an SVG", () => {
+ // Servers send either icon spelling, and `image/svg` turns up in place of the registered
+ // `image/svg+xml` often enough to be worth recognising.
+ for (const mime of [ "image/x-icon", "image/vnd.microsoft.icon", "image/svg", "image/svg+xml" ]) {
+ expect(isAcceptedImageMime(mime), mime).toBe(true);
+ }
+ });
+});
+
+describe("IMAGE_UPLOAD_SUBTYPES", () => {
+ it("is the same list with the type stripped, in the same order", () => {
+ expect(IMAGE_UPLOAD_SUBTYPES).toStrictEqual(IMAGE_MIMES.map((mime) => mime.replace("image/", "")));
+ // The editor builds `^image/(<joined>)$` out of these, so a subtype carrying the prefix
+ // would silently match nothing.
+ for (const subtype of IMAGE_UPLOAD_SUBTYPES) {
+ expect(subtype, subtype).not.toContain("/");
+ }
+ });
+});
diff --git a/packages/commons/src/lib/image_mimes.ts b/packages/commons/src/lib/image_mimes.ts
new file mode 100644
index 0000000000..7778bbc325
--- /dev/null
+++ b/packages/commons/src/lib/image_mimes.ts
@@ -0,0 +1,58 @@
+/**
+ * The media types Trilium handles as pictures, shared by the two places that decide it.
+ *
+ * The upload endpoints gate on this to choose between storing an image (an `image`-role attachment
+ * or an image note, addressed by an `api/attachments/.../image/...` URL) and storing an opaque file
+ * (addressed by a `#root/...?viewMode=attachments` reference). The rich text editor gates on the
+ * same thing to choose between inserting a picture and handing the file to the file-upload plugin.
+ *
+ * Those two used to be separate lists, and every type they disagreed about was a defect:
+ *
+ * - Claimed by the editor but not by the endpoint, the editor inserts an image element, uploads,
+ * and assigns whatever comes back as its source without looking at it — so the file branch's
+ * `#root/...` reference ended up in an `<img src>`, drawing a permanently broken picture.
+ * - Accepted by the endpoint but not claimed by the editor, the file-upload plugin builds a
+ * reference link out of it and points it at the image URL the endpoint answered with, which is
+ * not a note URL, so it renders as "[missing note]".
+ *
+ * Keeping one list means neither can happen. Consult it through {@link isAcceptedImageMime} where a
+ * media type is in hand, and through {@link IMAGE_UPLOAD_SUBTYPES} where the editor's config wants
+ * bare subtypes.
+ */
+export const IMAGE_MIMES = [
+ "image/png",
+ // Unregistered, but some clients send it for a JPEG.
+ "image/jpg",
+ "image/jpeg",
+ "image/gif",
+ "image/bmp",
+ "image/webp",
+ "image/avif",
+ // `image/svg` is unregistered too — `image/svg+xml` is the real one — but it costs nothing to
+ // recognise, and a document arriving under it is still a document.
+ "image/svg",
+ "image/svg+xml",
+ // Both spellings of an icon: `image/vnd.microsoft.icon` is the registered name and
+ // `image/x-icon` is what servers actually send.
+ "image/x-icon",
+ "image/vnd.microsoft.icon"
+] as const;
+
+/**
+ * TIFF is deliberately absent. No browser but Safari draws one in an `<img>`, so treating it as a
+ * picture produces an element that cannot render whichever side is asked; left off, it stores as a
+ * file and gets a working reference link instead.
+ */
+const ACCEPTED_IMAGE_MIMES: ReadonlySet<string> = new Set(IMAGE_MIMES);
+
+/** Whether an upload of this media type is to be handled as a picture. */
+export function isAcceptedImageMime(mime: string | undefined | null): boolean {
+ return !!mime && ACCEPTED_IMAGE_MIMES.has(mime);
+}
+
+/**
+ * The same list as the editor's `image.upload.types` wants it: bare subtypes, which it matches
+ * against a dropped file as `^image/(<one of these>)$`. Anchored, so every subtype has to appear in
+ * full — `svg` does not stand in for `svg+xml`.
+ */
+export const IMAGE_UPLOAD_SUBTYPES: readonly string[] = IMAGE_MIMES.map((mime) => mime.slice("image/".length));
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index e8708f0553..fab709fea1 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 { ACCEPTED_IMAGE_MIMES, default as imageService } from "./services/image";
+export { 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.ts b/packages/trilium-core/src/routes/api/attachments.ts
index c53311fc8e..c6c4500cb2 100644
--- a/packages/trilium-core/src/routes/api/attachments.ts
+++ b/packages/trilium-core/src/routes/api/attachments.ts
@@ -1,4 +1,4 @@
-import { ConvertAttachmentToNoteResponse } from "@triliumnext/commons";
+import { ConvertAttachmentToNoteResponse, isAcceptedImageMime } from "@triliumnext/commons";
import { ValidationError } from "../../errors";
import type { Request } from "express";
import type { File } from "../../services/import/common.js";
@@ -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, { ACCEPTED_IMAGE_MIMES } from "../../services/image.js";
+import imageService 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 (ACCEPTED_IMAGE_MIMES.has(file.mimetype)) {
+ if (isAcceptedImageMime(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 96b6e7b3f4..866b7040b2 100644
--- a/packages/trilium-core/src/routes/api/image.ts
+++ b/packages/trilium-core/src/routes/api/image.ts
@@ -1,4 +1,4 @@
-import { type ImageCompressionOptions, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
+import { type ImageCompressionOptions, isAcceptedImageMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
import type { Request, Response } from "express";
import type { File } from "../../services/import/common.js";
@@ -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, { ACCEPTED_IMAGE_MIMES } from "../../services/image.js";
+import imageService 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 (!ACCEPTED_IMAGE_MIMES.has(file.mimetype)) {
+ if (!isAcceptedImageMime(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 a4ecc54954..27f6300621 100644
--- a/packages/trilium-core/src/services/image.ts
+++ b/packages/trilium-core/src/services/image.ts
@@ -14,29 +14,6 @@ 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",
diff --git a/packages/trilium-core/src/services/image_inspect.spec.ts b/packages/trilium-core/src/services/image_inspect.spec.ts
index 1ee27b9b83..1c61f1a533 100644
--- a/packages/trilium-core/src/services/image_inspect.spec.ts
+++ b/packages/trilium-core/src/services/image_inspect.spec.ts
@@ -47,6 +47,11 @@ function ico(width: number, height: number): Uint8Array {
return bytes(0x00, 0x00, 0x01, 0x00, 0x01, 0x00, width & 0xff, height & 0xff);
}
+/** An ISO base media file: a box length, the `ftyp` tag, then the brand that says what it holds. */
+function isoBmff(brand: string): Uint8Array {
+ return bytes(0x00, 0x00, 0x00, 0x18, ...[ ..."ftyp" ].map((c) => c.charCodeAt(0)), ...[ ...brand ].map((c) => c.charCodeAt(0)));
+}
+
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) ]);
@@ -65,6 +70,14 @@ describe("inspectImage", () => {
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" });
+ expect(inspectImage(isoBmff("avif"))).toMatchObject({ format: "avif", mime: "image/avif" });
+ });
+
+ it("reads the AVIF sequence brand, which an <img> draws just the same", () => {
+ expect(inspectImage(isoBmff("avis")).format).toBe("avif");
+ // Other things are packed in the same container and are not pictures.
+ expect(inspectImage(isoBmff("mp42")).format).toBe(UNKNOWN_FORMAT);
+ expect(inspectImage(isoBmff("heic")).format).toBe(UNKNOWN_FORMAT);
});
it("does not read a cursor as an icon", () => {
diff --git a/packages/trilium-core/src/services/image_inspect.ts b/packages/trilium-core/src/services/image_inspect.ts
index ff1dd8a284..c3cc60590f 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", "ico", or {@link UNKNOWN_FORMAT}. */
+ /** "jpg", "png", "gif", "webp", "bmp", "svg", "ico", "avif", or {@link UNKNOWN_FORMAT}. */
format: string;
mime: string;
width: number | null;
@@ -96,6 +96,13 @@ function detectFormat(buffer: Uint8Array): string {
return "ico";
}
+ // An ISO base media file whose brand says AVIF: the box length comes first, so the signature
+ // starts four bytes in. `avis` is the sequence brand, which an <img> still draws.
+ if (startsWith(buffer.subarray(4), [ 0x66, 0x74, 0x79, 0x70 ])
+ && (startsWith(buffer.subarray(8), [ 0x61, 0x76, 0x69, 0x66 ]) || startsWith(buffer.subarray(8), [ 0x61, 0x76, 0x69, 0x73 ]))) {
+ return "avif";
+ }
+
return startsWith(buffer, [ 0x42, 0x4d ]) ? "bmp" : UNKNOWN_FORMAT;
}
@@ -264,5 +271,6 @@ const FORMAT_MIMES: Record<string, string> = {
bmp: "image/bmp",
svg: "image/svg+xml",
ico: "image/x-icon",
+ avif: "image/avif",
[UNKNOWN_FORMAT]: "application/octet-stream"
};