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(table): link a url cell only where its scheme is one we may link to
Elian Doran3c5442bb5ec3
diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.tsindex 051af6093d..a6fad15ec0 100644--- a/apps/client/src/widgets/collections/table/columns.spec.ts+++ b/apps/client/src/widgets/collections/table/columns.spec.ts@@ -1,6 +1,6 @@import { act } from "preact/test-utils";import { describe, expect, it, vi } from "vitest";-import { type AttributeDefinitionInformation, buildColumnDefinitions, formatLabelDate, restoreExistingData, type ValuesEditorParams } from "./columns";+import { type AttributeDefinitionInformation, buildColumnDefinitions, formatLabelDate, restoreExistingData, safeUrlHref, type ValuesEditorParams } from "./columns";import type { CellComponent, ColumnDefinition } from "tabulator-tables";import options from "../../../services/options";@@ -154,6 +154,21 @@ describe("buildColumnDefinitions — typed columns", () => {// A plain input here would be a text box to type "14:05" into by hand.expect(editorOf("time")).toBe("time");});++ it("hands a url column's href through the scheme guard rather than linking the value as stored", () => {+ const column = buildColumnDefinitions({+ info: [ { name: "site", type: "url" } ],+ movableRows: false,+ existingColumnData: undefined,+ rowNumberHint: 1+ }).find((column) => column.field === "labels.site");++ // Tabulator's link formatter assigns whatever it is given straight to the anchor's href.+ const url = (column?.formatterParams as { url?: (cell: CellComponent) => string })?.url;+ if (typeof url !== "function") throw new Error("expected the href to be built by a callback");+ expect(url({ getValue: () => "javascript:alert(1)" } as CellComponent)).toBe("about:blank");+ expect(url({ getValue: () => "https://example.com" } as CellComponent)).toBe("https://example.com");+ });});describe("buildColumnDefinitions — colour columns", () => {@@ -379,6 +394,20 @@ describe("buildColumnDefinitions — multi-valued columns", () => {.toBe("#ff2e88");});+ it("links each url of a set, without making a hostile scheme clickable", () => {+ const formatter = multiColumn("url")?.formatter;+ if (typeof formatter !== "function") throw new Error("expected a formatter of its own");+ const cell = formatter(+ { getValue: () => [ "example.com", "javascript:alert(1)" ] } as CellComponent,+ { type: "url" }, () => {}+ ) as HTMLElement;++ expect([ ...cell.querySelectorAll("a") ].map((link) => link.getAttribute("href")))+ .toEqual([ "https://example.com", "about:blank" ]);+ // The value is still readable even where it is not one we may link to.+ expect(cell.textContent).toContain("javascript:alert(1)");+ });+it("sorts by the values a cell holds, not by the array they arrive in", () => {const sorter = multiColumn("text")?.sorter;if (typeof sorter !== "function") throw new Error("expected a sorter of its own");@@ -391,6 +420,31 @@ describe("buildColumnDefinitions — multi-valued columns", () => {});});+describe("safeUrlHref", () => {+ it("keeps the schemes a link may carry, and defaults the one a bare address is missing", () => {+ expect(safeUrlHref("https://example.com/a?b=c#d")).toBe("https://example.com/a?b=c#d");+ expect(safeUrlHref("http://example.com")).toBe("http://example.com");+ // Linked as stored, a bare address would resolve against Trilium's own origin.+ expect(safeUrlHref("example.com/path")).toBe("https://example.com/path");+ expect(safeUrlHref(" example.com ")).toBe("https://example.com");+ });++ it("makes an executable scheme inert instead of clickable", () => {+ // A label's value can arrive from an import or a sync peer, so clicking a cell must not run it.+ expect(safeUrlHref("javascript:alert(1)")).toBe("about:blank");+ expect(safeUrlHref("JavaScript:alert(1)")).toBe("about:blank");+ expect(safeUrlHref(" javascript:alert(1)")).toBe("about:blank");+ expect(safeUrlHref("data:text/html,<script>alert(1)</script>")).toBe("about:blank");+ expect(safeUrlHref("vbscript:msgbox(1)")).toBe("about:blank");+ });++ it("renders a blank href for missing values", () => {+ expect(safeUrlHref(undefined)).toBe("");+ expect(safeUrlHref(null)).toBe("");+ expect(safeUrlHref(" ")).toBe("");+ });+});+describe("formatLabelDate", () => {it("renders dates and datetimes in the configured formatting locale", () => {options.set("formattingLocale", "de");diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsxindex 66cd6e96f4..d6570df934 100644--- a/apps/client/src/widgets/collections/table/columns.tsx+++ b/apps/client/src/widgets/collections/table/columns.tsx@@ -1,6 +1,6 @@import "./columns.css";-import { LabelType } from "@triliumnext/commons";+import { LabelType, safeLinkPreviewHref } from "@triliumnext/commons";import clsx from "clsx";import { JSX } from "preact";import { useEffect, useRef, useState } from "preact/hooks";@@ -73,6 +73,9 @@ const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {},url: {formatter: "link",+ formatterParams: {+ url: (cell) => safeUrlHref(cell.getValue())+ },editor: "input"},email: {@@ -107,6 +110,19 @@ function applyLinkScheme(value: unknown, scheme: string): string {return value.startsWith(scheme) ? value : `${scheme}${value}`;}+/**+ * The `href` a url value may be linked as. A label's value is free text that can have arrived from an+ * import or a sync peer, so a hostile scheme (`javascript:`, `data:`) is made inert rather than+ * clickable; a value carrying no scheme at all gets the `https://` an address bar would give it,+ * rather than being linked as a path relative to Trilium itself.+ */+export function safeUrlHref(value: unknown): string {+ if (typeof value !== "string" || !value.trim()) return "";++ const trimmed = value.trim();+ return safeLinkPreviewHref(/^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`);+}+/*** Renders a stored date label through the user's formatting locale, all-numeric so that columns stay* narrow and every locale shows a four-digit year.@@ -469,8 +485,8 @@ function ValuesFormatter({ cell, formatterParams }: FormatterOpts) {);}-/** The schemes that make a value of a link-like type clickable; a url carries its own. */-const LINK_SCHEMES: Partial<Record<ColumnType, string>> = { url: "", email: "mailto:", phone: "tel:" };+/** The schemes that make a value of a link-like type clickable; a url is linked by {@link safeUrlHref}. */+const LINK_SCHEMES: Partial<Record<ColumnType, string>> = { email: "mailto:", phone: "tel:" };/** The whole of what a flag can be, which is what a column of flags picks its values from. */const BOOLEAN_OPTIONS = [ "true", "false" ];@@ -492,6 +508,10 @@ function renderValue(value: string, type: ColumnType | undefined) {return renderFlag(value);}+ if (type === "url") {+ return <a href={safeUrlHref(value)}>{value}</a>;+ }+const scheme = type && LINK_SCHEMES[type];return scheme !== undefined? <a href={applyLinkScheme(value, scheme)}>{value}</a>