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
text editor/link previews: do not autolink URLs if their metadata is not available
Adorian Doran9f91863af87c
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.tsindex 567ca75d36..9e4f476aa5 100644--- a/apps/client/src/services/link_embed.spec.ts+++ b/apps/client/src/services/link_embed.spec.ts@@ -90,9 +90,23 @@ describe("fetchMetadata", () => {expect(result).toEqual({url: "https://youtu.be/abcdefghijk",embedType: "youtube",- title: "youtu.be"+ title: "youtu.be",+ // Nothing was actually read about the page, so callers can keep a plain link instead.+ unresolved: true});});++ it("passes the server's unresolved flag through", async () => {+ server.get = vi.fn(async () => ({+ url: "https://blocked.example.com/x",+ embedType: "opengraph",+ title: "blocked.example.com",+ unresolved: true+ })) as typeof server.get;++ const result = await fetchMetadata("https://blocked.example.com/x");+ expect(result.unresolved).toBe(true);+ });});describe("renderEmbedPreview", () => {diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsxindex a3d5029cbd..dae6d3e7b6 100644--- a/apps/client/src/services/link_embed.tsx+++ b/apps/client/src/services/link_embed.tsx@@ -17,6 +17,8 @@ export interface EmbedMetadata {favicon?: string;siteName?: string;image?: string;+ /** See {@link LinkEmbedMetadata.unresolved}. Not persisted into the note's HTML. */+ unresolved?: boolean;}@@ -42,13 +44,15 @@ export async function fetchMetadata(url: string): Promise<EmbedMetadata> {description: metadata.description,favicon: metadata.favicon,siteName: metadata.siteName,- image: metadata.image+ image: metadata.image,+ unresolved: metadata.unresolved};} catch {return {url,embedType: detectEmbedType(url),- title: safeHostname(url)+ title: safeHostname(url),+ unresolved: true};}}diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.tsindex 0da62864e4..eff9ac9845 100644--- a/apps/server/src/routes/api/link_embed.spec.ts+++ b/apps/server/src/routes/api/link_embed.spec.ts@@ -88,10 +88,26 @@ describe("link-embed getMetadata", () => {expect(result.siteName).toBe("Example");});- it("falls back to the hostname when the fetch fails", async () => {+ it("falls back to the hostname when the fetch fails, flagging the result unresolved", async () => {safeFetch.mockResolvedValue(fakeResponse("", { ok: false }));const result = await linkEmbedRoute.getMetadata(req("https://broken.example.com/x"));- expect(result).toEqual({ url: "https://broken.example.com/x", title: "broken.example.com", embedType: "opengraph" });+ expect(result).toEqual({ url: "https://broken.example.com/x", title: "broken.example.com", embedType: "opengraph", unresolved: true });+ });++ it("treats a page carrying no title of its own as unresolved", async () => {+ // A bot-challenge interstitial (or any titleless page) answers 200 with HTML but names+ // nothing, leaving us with the hostname we already had.+ safeFetch.mockResolvedValue(fakeResponse("<html><head></head><body>nope</body></html>", { contentType: "text/html" }));+ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result).toEqual({ url: "https://example.com/page", title: "example.com", embedType: "opengraph", unresolved: true });+ });++ it("does not flag a successfully scraped page", async () => {+ const html = `<html><head><title>Real Page</title></head></html>`;+ safeFetch.mockResolvedValue(fakeResponse(html, { contentType: "text/html" }));+ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result.title).toBe("Real Page");+ expect(result.unresolved).toBeUndefined();});it("uses a generic YouTube title when oEmbed is unavailable", async () => {@@ -107,7 +123,13 @@ describe("link-embed getMetadata", () => {it("falls back when the page is not HTML", async () => {safeFetch.mockResolvedValue(fakeResponse("not html", { contentType: "application/json" }));const result = await linkEmbedRoute.getMetadata(req("https://example.com/data.json"));- expect(result).toEqual({ url: "https://example.com/data.json", title: "example.com", embedType: "opengraph" });+ expect(result).toEqual({ url: "https://example.com/data.json", title: "example.com", embedType: "opengraph", unresolved: true });+ });++ it("keeps a YouTube link resolved even when oEmbed fails, since the player needs no metadata", async () => {+ safeFetch.mockResolvedValue(fakeResponse("", { ok: false }));+ const result = await linkEmbedRoute.getMetadata(req("https://youtu.be/dQw4w9WgXcQ"));+ expect(result.unresolved).toBeUndefined();});it("ignores a favicon that advertises a size over the limit", async () => {diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.tsindex 7399450cda..04bfcaf004 100644--- a/apps/server/src/routes/api/link_embed.ts+++ b/apps/server/src/routes/api/link_embed.ts@@ -1,9 +1,8 @@-import { extractYouTubeVideoId,type LinkEmbedMetadata } from "@triliumnext/commons";-import { ValidationError } from "@triliumnext/core";+import { extractYouTubeVideoId, type LinkEmbedMetadata } from "@triliumnext/commons";+import { getLog, ValidationError } from "@triliumnext/core";import type { Request } from "express";import { parse } from "node-html-parser";-import { getLog } from "@triliumnext/core";import { safeFetch, validateUrl } from "../../services/safe_fetch.js";const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB@@ -181,12 +180,21 @@ async function getMetadata(req: Request) {const url = validatedUrl.toString();const videoId = extractYouTubeVideoId(url);+ // A YouTube link stays resolved even when oEmbed is unreachable: the player embeds from the+ // video ID alone, so the preview is worth showing with or without the title and channel.if (videoId) {return await fetchYouTubeMetadata(url, videoId);}try {const ogData = await fetchOpenGraphData(url);++ // A page that answered but names itself nowhere (no og:title, no <title>) leaves us with+ // the hostname we already had, which is no better than a failed fetch.+ if (!ogData.title) {+ return unresolvedMetadata(validatedUrl);+ }+return {url,title: ogData.title,@@ -198,12 +206,22 @@ async function getMetadata(req: Request) {} satisfies LinkEmbedMetadata;} catch (e: unknown) {getLog().info(`Failed to fetch metadata for ${url}: ${e}`);- return {- url,- title: validatedUrl.hostname,- embedType: "opengraph"- } satisfies LinkEmbedMetadata;+ return unresolvedMetadata(validatedUrl);}}+/**+ * The degraded result for a URL whose page told us nothing: everything the caller gets back is+ * derived from the URL itself. Flagged so the caller can keep a plain link instead of rendering a+ * preview that would show less than the link did.+ */+function unresolvedMetadata(url: URL): LinkEmbedMetadata {+ return {+ url: url.toString(),+ title: url.hostname,+ embedType: "opengraph",+ unresolved: true+ };+}+export default { getMetadata };diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 7ebad27190..263503cf4f 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -13,6 +13,13 @@ declare global {favicon?: string;siteName?: string;image?: string;+ /**+ * True when the host could not read the page (network error, bot challenge, non-HTML+ * response, or a page with no title of its own) and the fields above hold nothing but a+ * hostname-derived placeholder. Mirrors `LinkEmbedMetadata.unresolved` in+ * `@triliumnext/commons`, which is what the host actually returns.+ */+ unresolved?: boolean;}interface EditorComponent extends Component {diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.tsindex dd929b0a3a..64ca1dc055 100644--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts+++ b/packages/ckeditor5/src/plugins/linkembed.spec.ts@@ -17,7 +17,10 @@ import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND } from "./liconst META = {url: "https://example.com/",- embedType: "web",+ // The host only ever reports "youtube" or "opengraph". It matters here that this is the real+ // thing: chooseLinkPreviewKind() treats anything other than "opengraph" as embeddable, so a made-up+ // type would send a URL standing alone in its block down the block-embed path instead of the mention one.+ embedType: "opengraph",title: "Example title",description: "Some description",favicon: "https://example.com/favicon.ico",@@ -395,6 +398,24 @@ describe("LinkEmbed", () => {expect(mention?.getAttribute("title")).toBe(META.title);});+ it("leaves the plain link untouched when the metadata could not be resolved, and says why", async () => {+ const url = "https://blocked.example.com/article";+ fetchLinkMetadata.mockResolvedValueOnce({ url, embedType: "opengraph", title: "blocked.example.com", unresolved: true });+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});++ addLinkedText(editor, url);+ await flushFetch();++ expect(fetchLinkMetadata).toHaveBeenCalledWith(url);+ expect(findElement(editor, "linkMention")).toBeUndefined();+ expect(findElement(editor, "linkEmbed")).toBeUndefined();+ // The link AutoLink created is still there, as plain linked text.+ expect(editor.getData()).toContain(`<a href="${url}">${url}</a>`);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(url));++ warn.mockRestore();+ });+it("ignores a labeled link whose text differs from the href", async () => {addLinkedText(editor, "https://example.com/article", "click here");@@ -671,9 +692,12 @@ function addLinkedText(editor: ClassicEditor, href: string, text = href): void {});}-/** Lets the `fetchLinkMetadata().then(...)` microtask chain resolve. */+/**+ * Lets the `fetchLinkMetadata().then(...)` chain resolve and the resulting model change apply.+ * A task turn is awaited rather than a fixed number of microtasks: the latter is a guess at the+ * chain's depth that silently under-waits, which makes a conversion test fail and — worse — makes a+ * test asserting that NO conversion happened pass for the wrong reason.+ */async function flushFetch(): Promise<void> {- await Promise.resolve();- await Promise.resolve();- await Promise.resolve();+ await new Promise((resolve) => setTimeout(resolve, 0));}diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.tsindex cf1044c3ea..54c8b8afc2 100644--- a/packages/ckeditor5/src/plugins/linkembed.ts+++ b/packages/ckeditor5/src/plugins/linkembed.ts@@ -431,6 +431,14 @@ class AutoLinkToMention extends Plugin {const component = glob.getComponentByEl<EditorComponent>(editorEl);component.fetchLinkMetadata(url).then((metadata: LinkEmbedMetadata) => {+ // The page told us nothing (bot challenge, network error, no title of its own): leave the+ // plain link AutoLink already created. A preview built from a hostname placeholder would+ // show strictly less than the URL it replaced.+ if (metadata.unresolved) {+ console.warn(`Link preview dropped for ${url}: no metadata could be read from the page (kept as a plain link).`);+ return;+ }+this._converting = true;editor.model.change((writer) => {diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.tsindex 1ceddac74d..2411128caf 100644--- a/packages/commons/src/lib/link_embed.ts+++ b/packages/commons/src/lib/link_embed.ts@@ -13,6 +13,14 @@ export interface LinkEmbedMetadata {favicon?: string;siteName?: string;embedType: "youtube" | "opengraph";+ /**+ * True when the page could not be read at all — a network error, a bot challenge (many sites+ * answer a server-side fetch with a Cloudflare interstitial), a non-HTML response, or a page+ * carrying no title of its own. The remaining fields then hold nothing but a hostname-derived+ * placeholder, so an auto-detected URL is left as a plain link rather than becoming a preview+ * that shows less than the URL itself did. Never persisted into the note's HTML.+ */+ unresolved?: boolean;}/**