Skip to content

Build your personal knowledge base with Trilium Notes

feat(link-preview): move the route into core so standalone serves it too

Elian Doran43faaf5968c9
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 2e2f5ed64b..5c9008bae5 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -24,7 +24,6 @@ import etapiTokensApiRoutes from "./api/etapi_tokens.js";
import filesRoute from "./api/files.js";
import fontsRoute from "./api/fonts.js";
// API routes
-import linkEmbedRoute from "./api/link_embed.js";
import llmChatRoute from "./api/llm_chat.js";
import llmSpecialNotesRoute from "./api/llm_special_notes.js";
import loginApiRoute from "./api/login.js";
@@ -185,7 +184,6 @@ function register(app: express.Application) {
// POST rather than GET: the URL would otherwise sit in the query string of every access-log
// line (Trilium's own, and any reverse proxy in front of it), and a pasted URL can carry a
// one-time token or a signed signature. The body is not logged.
- asyncApiRoute(PST, "/api/link-embed/metadata", linkEmbedRoute.getMetadata);
asyncApiRoute(PST, "/api/onenote-import/device-login", onenoteImportRoute.deviceLogin);
asyncApiRoute(PST, "/api/onenote-import/device-poll", onenoteImportRoute.devicePoll);
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/packages/trilium-core/src/routes/api/link_embed.spec.ts
similarity index 87%
rename from apps/server/src/routes/api/link_embed.spec.ts
rename to packages/trilium-core/src/routes/api/link_embed.spec.ts
index 8e1b348c76..07a513211f 100644
--- a/apps/server/src/routes/api/link_embed.spec.ts
+++ b/packages/trilium-core/src/routes/api/link_embed.spec.ts
@@ -1,18 +1,15 @@
import { extractYouTubeVideoId } from "@triliumnext/commons";
-import { ValidationError } from "@triliumnext/core";
-import imageService from "@triliumnext/core/src/services/image.js";
import type { Request } from "express";
import { Jimp } from "jimp";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const safeFetch = vi.hoisted(() => vi.fn());
-
-vi.mock("../../services/safe_fetch.js", () => ({
- // Bypass SSRF/DNS checks in tests — just parse the URL.
- validateUrl: (u: string) => new URL(u),
- safeFetch: (...args: unknown[]) => safeFetch(...args)
-}));
+import { ValidationError } from "../../errors.js";
+import imageService from "../../services/image.js";
+import { getImageProvider, type ImageProvider, initImageProvider } from "../../services/image_provider.js";
+import { initRequest, readCappedResponse } from "../../services/request.js";
+import { fakeRequestProvider } from "../../test/request_provider.js";
+const safeFetch = vi.hoisted(() => vi.fn());
const saveImageToAttachment = vi.hoisted(() => vi.fn());
const awaitImageWrite = vi.hoisted(() => vi.fn(async () => {}));
@@ -39,6 +36,16 @@ beforeEach(() => {
vi.spyOn(imageService, "saveImageToAttachment").mockImplementation(saveImageToAttachment);
vi.spyOn(imageService, "awaitImageWrite").mockImplementation(awaitImageWrite);
+
+ installResizer(resizeWithJimp);
+
+ // The route reaches the network through the request provider, so that is where the network is
+ // stood in for. Only the getting of the response is faked: what the tests hand back goes through
+ // the real readCappedResponse, so the ceilings and the content-type handling under test here are
+ // the ones that will run in production rather than a second implementation of them.
+ initRequest(fakeRequestProvider({
+ fetchResource: async (url, opts) => readCappedResponse(await safeFetch(url, opts), opts.maxBytes)
+ }));
});
/** What was handed to the attachment store under a given role, if anything was. */
@@ -48,31 +55,67 @@ function stored(role: "favicon" | "coverImage") {
return call ? { buffer: Buffer.from(call[1] as Uint8Array), fileName: call[2] as string } : undefined;
}
-function oneShotReader(bytes: Buffer) {
- let sent = false;
- return {
- async read() {
- if (sent) return { done: true, value: undefined };
- sent = true;
- return { done: false, value: new Uint8Array(bytes) };
- },
- async cancel() {}
- };
+/**
+ * Puts a known resizer behind the route.
+ *
+ * This spec runs under both test projects, and they install different image providers — the server's
+ * decodes, standalone's has no decoder at all. Left to whichever one the runtime bootstrapped, half
+ * these tests would assert a resize under one and its absence under the other. So the provider is
+ * chosen here instead, and what the route does with each kind of answer is tested deliberately
+ * rather than by whichever project happened to run it.
+ */
+function installResizer(resizeForPreview: ImageProvider["resizeForPreview"]) {
+ initImageProvider({ ...getImageProvider(), resizeForPreview });
}
+/**
+ * A resizer that really resizes, standing in for the platform implementation.
+ *
+ * Deliberately the same shape as the server's, since that is what the route is written against. It
+ * is not the same code: the real one lives in the server package with Jimp, along with its own
+ * tests. What is under test here is the route's handling of an answer, not the making of one.
+ */
+const resizeWithJimp: ImageProvider["resizeForPreview"] = async (bytes, { maxEdge, jpegQuality }) => {
+ try {
+ const image = await Jimp.fromBuffer(Buffer.from(bytes));
+
+ if (image.bitmap.width > maxEdge || image.bitmap.height > maxEdge) {
+ image.scaleToFit({ w: maxEdge, h: maxEdge });
+ }
+
+ return {
+ resized: true,
+ bytes: new Uint8Array(image.hasAlpha()
+ ? await image.getBuffer("image/png")
+ : await image.getBuffer("image/jpeg", { quality: jpegQuality }))
+ };
+ } catch {
+ return { resized: false, reason: "undecodable" };
+ }
+};
+
+/** What a runtime with no decoder answers — standalone, and the server for a format Jimp refuses. */
+const noResizer: ImageProvider["resizeForPreview"] = async () => ({
+ resized: false,
+ reason: "unsupported-platform"
+});
+
+/**
+ * What a site answers with, as a real `Response` — so the reading of it is the real reading of it.
+ *
+ * `json` is a convenience for an oEmbed answer: the payload *is* the JSON, since that is what the
+ * route now parses rather than asking a response object to do it.
+ */
function fakeResponse(payload: string | Buffer, opts: { ok?: boolean; contentType?: string; json?: unknown } = {}) {
- const buf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
- const headers: Record<string, string | null> = {
- "content-type": opts.contentType ?? "text/html",
- "content-length": String(buf.byteLength)
- };
- return {
- ok: opts.ok ?? true,
+ const body = opts.json !== undefined ? Buffer.from(JSON.stringify(opts.json)) : Buffer.from(payload);
+
+ return new Response(body, {
status: opts.ok === false ? 500 : 200,
- headers: { get: (h: string) => headers[h.toLowerCase()] ?? null },
- body: { getReader: () => oneShotReader(buf) },
- json: async () => opts.json
- };
+ headers: {
+ "content-type": opts.contentType ?? "text/html",
+ "content-length": String(body.byteLength)
+ }
+ });
}
/** A real, decodable PNG so the image pipeline runs for true rather than against a mock. */
@@ -81,6 +124,24 @@ async function makePng(width: number, height: number, color: number) {
return Buffer.from(await image.getBuffer("image/png"));
}
+/**
+ * A PNG that is genuinely large, for the ceilings that are about bytes rather than pixels.
+ *
+ * Noise, because a flat colour of any dimensions compresses to a few KB — a 2000x2000 one lands
+ * under even the 100KB verbatim cap, so a test written with one would pass while proving nothing.
+ */
+async function makeNoisyPng(edge: number) {
+ const image = new Jimp({ width: edge, height: edge, color: 0x000000ff });
+
+ for (let i = 0; i < image.bitmap.data.length; i += 4) {
+ image.bitmap.data[i] = (i * 7919) % 256;
+ image.bitmap.data[i + 1] = (i * 104729) % 256;
+ image.bitmap.data[i + 2] = (i * 15485863) % 256;
+ }
+
+ 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.
@@ -300,6 +361,41 @@ describe("link-embed getMetadata", () => {
serveImage({ payload: "<html>404</html>", contentType: "text/html" });
expect(await imageOf()).toBeUndefined();
});
+
+ /**
+ * The runtime with no decoder — standalone, where there is no image library at all. The
+ * preview must survive it: a cover small enough to keep is kept exactly as it arrived, which
+ * is still stored rather than hotlinked, and one too large is dropped so a note does not
+ * take a megabyte of someone else's picture to show a card.
+ *
+ * This is the same path the server already takes for a WebP its own decoder refuses, which
+ * is why there is no third behaviour to write — only a second runtime reaching the second.
+ */
+ describe("where nothing can scale the picture", () => {
+ beforeEach(() => installResizer(noResizer));
+
+ it("keeps a cover image of a storable size exactly as it arrived", async () => {
+ const png = await makePng(400, 400, 0x336699ff);
+ serveImage({ payload: png, contentType: "image/png" });
+
+ const image = await imageOf();
+ expect(image?.fileName).toMatch(/\.png$/);
+ // Unscaled and byte-for-byte what the site served.
+ expect(image?.buffer.equals(png)).toBe(true);
+ });
+
+ it("drops a cover image too large to keep unscaled, leaving the rest of the preview", async () => {
+ // Noise rather than a flat colour: a solid 2000x2000 PNG compresses to a few KB and
+ // would sail under the verbatim cap this is about.
+ serveImage({ payload: await makeNoisyPng(600), contentType: "image/png" });
+
+ expect(await imageOf()).toBeUndefined();
+
+ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
+ expect(result.unresolved).toBeFalsy();
+ expect(result.title).toBeTruthy();
+ });
+ });
});
describe("falling back to the site icon when there is no og:image", () => {
@@ -680,14 +776,13 @@ describe("link-embed getMetadata", () => {
it("treats a bodyless or content-type-less page response as unresolved", async () => {
// No body: there is no HTML to read, so the page names itself nowhere.
- safeFetch.mockResolvedValue({ ...fakeResponse("<html><head><title>T</title></head></html>"), body: undefined });
+ safeFetch.mockResolvedValue(new Response(null, { headers: { "content-type": "text/html" } }));
let result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
expect(result.unresolved).toBe(true);
- // No content-type header at all: not provably HTML, same as a wrong content type.
- const response = fakeResponse("<html><head><title>T</title></head></html>");
- response.headers = { get: () => null };
- safeFetch.mockResolvedValue(response);
+ // No content-type header at all: not provably HTML, same as a wrong content type. A byte
+ // body is what makes that reachable — a string one would have fetch name it text/plain.
+ safeFetch.mockResolvedValue(new Response(Buffer.from("<html><head><title>T</title></head></html>")));
result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
expect(result.unresolved).toBe(true);
});
diff --git a/apps/server/src/routes/api/link_embed.ts b/packages/trilium-core/src/routes/api/link_embed.ts
similarity index 88%
rename from apps/server/src/routes/api/link_embed.ts
rename to packages/trilium-core/src/routes/api/link_embed.ts
index 16716e0592..a9b6b55463 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/packages/trilium-core/src/routes/api/link_embed.ts
@@ -5,18 +5,22 @@ import {
linkPreviewImageName,
safeHostname
} from "@triliumnext/commons";
-import { getLog, imageService, ValidationError } from "@triliumnext/core";
-import { trimIcoToSmallestEntry } from "@triliumnext/core/src/services/ico.js";
-import { storePictureBytes } from "@triliumnext/core/src/services/image_download.js";
-import { type InspectedImage, inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";
-import { getImageProvider } from "@triliumnext/core/src/services/image_provider.js";
-import { findPageDescription } from "@triliumnext/core/src/services/page_description.js";
import type { Request } from "express";
import { parse } from "node-html-parser";
-import { safeFetch, validateUrl } from "../../services/safe_fetch.js";
+import { ValidationError } from "../../errors.js";
+import { trimIcoToSmallestEntry } from "../../services/ico.js";
+import imageService from "../../services/image.js";
+import { storePictureBytes } from "../../services/image_download.js";
+import { type InspectedImage, inspectImage, UNKNOWN_FORMAT } from "../../services/image_inspect.js";
+import { getImageProvider } from "../../services/image_provider.js";
+import { getLog } from "../../services/log.js";
+import { findPageDescription } from "../../services/page_description.js";
+import request, { type FetchedResource, validateFetchableUrl } from "../../services/request.js";
const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB
+/** An oEmbed answer is a handful of fields; anything approaching this is not one. */
+const MAX_OEMBED_SIZE = 64 * 1024; // 64KB
/**
* How much of a favicon to fetch.
@@ -69,84 +73,40 @@ const MAX_ICON_CANDIDATES = 3;
const MAX_FAVICON_CANDIDATES = 3;
/**
- * Reads the response body as text, stopping after maxBytes to avoid
- * buffering arbitrarily large responses into memory.
+ * A fetched resource read as text.
+ *
+ * Decoded as UTF-8 without exception, which is what the previous streaming read did as well. A page
+ * declaring some other encoding comes out mangled in its non-ASCII characters — but the tags this
+ * reads are ASCII, so it still finds them, and the alternative is carrying a charset decoder for the
+ * sake of a title that is occasionally accented.
*/
-async function readResponseText(response: Response, maxBytes: number): Promise<string> {
- const reader = response.body?.getReader();
- if (!reader) return "";
-
- const decoder = new TextDecoder();
- let result = "";
- let bytesRead = 0;
-
- while (bytesRead < maxBytes) {
- const { done, value } = await reader.read();
- if (done) break;
-
- bytesRead += value.byteLength;
- result += decoder.decode(value, { stream: true });
- }
-
- void reader.cancel();
- return result.slice(0, maxBytes);
+function asText({ bytes }: FetchedResource): string {
+ return new TextDecoder().decode(bytes);
}
/**
- * 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.
+ * Downloads a binary resource, or nothing where it could not be had.
+ *
+ * The ceiling, the streaming and the vetting of the address all belong to the request provider now,
+ * which is what lets this run on a runtime with no Node in it. What is left here is the one decision
+ * that is this route's rather than the transport's: a preview would rather go without a picture than
+ * fail, so every way of not getting one collapses to the same absence.
+ *
+ * `defaultContentType` stands in where a server named none — an `.ico` is routinely served as
+ * `application/octet-stream`, or as nothing at all.
*/
async function downloadBinary(url: string, maxBytes: number, defaultContentType: string): Promise<{ bytes: Uint8Array; contentType: string } | undefined> {
try {
- const response = await safeFetch(url);
+ const response = await request.fetchResource(url, { maxBytes });
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) > maxBytes) return undefined;
-
- 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();
- if (!reader) return undefined;
-
- const chunks: Uint8Array[] = [];
- let bytesRead = 0;
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- bytesRead += value.byteLength;
- if (bytesRead > maxBytes) {
- void reader.cancel();
- return undefined;
- }
- chunks.push(value);
- }
-
- return { bytes: concatChunks(chunks, bytesRead), contentType };
+ return { bytes: response.bytes, contentType: response.contentType || defaultContentType };
} catch {
return undefined;
}
}
-/** Joins the pieces a streamed body arrived in into the single buffer the rest of the code wants. */
-function concatChunks(chunks: Uint8Array[], totalLength: number): Uint8Array {
- const joined = new Uint8Array(totalLength);
- let offset = 0;
-
- for (const chunk of chunks) {
- joined.set(chunk, offset);
- offset += chunk.byteLength;
- }
-
- return joined;
-}
-
/** A picture that has been fetched and identified, but not yet stored anywhere. */
interface DownloadedPicture {
bytes: Uint8Array;
@@ -372,7 +332,7 @@ function collectIconCandidates(document: ReturnType<typeof parse>, pageUrl: stri
candidates.sort((a, b) => b.size - a.size);
const urls = candidates.map((candidate) => candidate.url);
- // `pageUrl` already passed validateUrl, so resolving the conventional path against it cannot fail.
+ // `pageUrl` already passed validateFetchableUrl, so resolving the conventional path against it cannot fail.
const conventional = new URL("/apple-touch-icon.png", pageUrl).toString();
if (!urls.includes(conventional)) {
urls.push(conventional);
@@ -454,7 +414,7 @@ function collectFaviconCandidates(document: ReturnType<typeof parse>, pageUrl: s
const urls = [ ...new Set(candidates.map((candidate) => candidate.url)) ].slice(0, MAX_FAVICON_CANDIDATES);
// Every site is entitled to serve this whether it declares it or not, so it is the last resort
- // rather than one of the ranked candidates. `pageUrl` already passed validateUrl, so it forms a
+ // rather than one of the ranked candidates. `pageUrl` already passed validateFetchableUrl, so it forms a
// URL. Appended after the cap, never dropped by it.
const conventional = new URL("/favicon.ico", pageUrl).toString();
if (!urls.includes(conventional)) {
@@ -530,11 +490,11 @@ async function fetchYouTubeMetadata(url: string, videoId: string): Promise<Fetch
try {
const oembedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(url)}&format=json`;
- const response = await safeFetch(oembedUrl);
+ const response = await request.fetchResource(oembedUrl, { maxBytes: MAX_OEMBED_SIZE });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
- const data = await response.json();
+ const data = JSON.parse(asText(response));
if (data.title) metadata.title = data.title;
if (data.author_name) metadata.description = data.author_name;
if (data.thumbnail_url) thumbnailUrl = data.thumbnail_url;
@@ -548,7 +508,8 @@ async function fetchYouTubeMetadata(url: string, videoId: string): Promise<Fetch
}
async function fetchOpenGraphData(url: string) {
- const response = await safeFetch(url, {
+ const response = await request.fetchResource(url, {
+ maxBytes: MAX_RESPONSE_SIZE,
headers: {
"User-Agent": "TriliumNotes/1.0 (Link Preview; +https://triliumnotes.org/)",
"Accept": "text/html"
@@ -557,13 +518,12 @@ async function fetchOpenGraphData(url: string) {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
- const contentType = response.headers.get("content-type") || "";
+ const { contentType } = response;
if (!contentType.includes("text/html") && !contentType.includes("application/xhtml+xml")) {
throw new Error(`Unexpected Content-Type: ${contentType}`);
}
- const html = await readResponseText(response, MAX_RESPONSE_SIZE);
- const document = parse(html);
+ const document = parse(asText(response));
const getMeta = (property: string): string | undefined => {
const ogEl = document.querySelector(`meta[property="${property}"]`);
@@ -618,7 +578,7 @@ async function getMetadata(req: Request) {
throw new ValidationError("'noteId' is required");
}
- const validatedUrl = validateUrl(urlParam);
+ const validatedUrl = validateFetchableUrl(urlParam);
const url = validatedUrl.toString();
const videoId = extractYouTubeVideoId(url);
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 57a7d60f47..137562b99d 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -34,6 +34,7 @@ import backendLogRoute from "./api/backend_log";
import backupRoute from "./api/backup";
import passwordApiRoute from "./api/password";
import loginApiRoute from "./api/login";
+import linkEmbedRoute from "./api/link_embed";
// TODO: Deduplicate with routes.ts
const GET = "get",
@@ -142,6 +143,10 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
asyncApiRoute(PST, "/api/attachments/:attachmentId/compress-image", imageRoute.compressAttachmentImage);
asyncRoute(PST, "/api/notes/:noteId/attachments/upload", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);
+ // POSTed rather than taking the URL in a query string: a link can carry a one-time token or a
+ // signature, and a query string ends up in every access log along the way.
+ asyncApiRoute(PST, "/api/link-embed/metadata", linkEmbedRoute.getMetadata);
+
// group of the services below are meant to be executed from the outside
route(GET, "/api/setup/status", [], setupApiRoute.getStatus, apiResultHandler);
asyncRoute(PST, "/api/setup/new-document", [checkAppNotInitialized], setupApiRoute.setupNewDocument, apiResultHandler);