Skip to content

Build your personal knowledge base with Trilium Notes

fix(attributes): open a url label only where its scheme is one we may follow

Elian Doran39a1f0088e06
diff --git a/apps/client/src/utils/url.spec.ts b/apps/client/src/utils/url.spec.ts
new file mode 100644
index 0000000000..9edb4f0ed4
--- /dev/null
+++ b/apps/client/src/utils/url.spec.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+
+import { normalizeExternalUrl, safeUrlHref } from "./url";
+
+describe("normalizeExternalUrl", () => {
+ it("keeps the schemes an address may carry, and defaults the one a bare address is missing", () => {
+ expect(normalizeExternalUrl("https://example.com/a?b=c#d")).toBe("https://example.com/a?b=c#d");
+ expect(normalizeExternalUrl("http://example.com")).toBe("http://example.com");
+ // Followed as stored, a bare address would resolve against Trilium's own origin.
+ expect(normalizeExternalUrl("example.com/path")).toBe("https://example.com/path");
+ expect(normalizeExternalUrl(" example.com ")).toBe("https://example.com");
+ });
+
+ it("rejects a scheme that would run in Trilium's own origin", () => {
+ // A label's value can arrive from an import or a sync peer, so following one must not run it.
+ expect(normalizeExternalUrl("javascript:alert(1)")).toBeNull();
+ expect(normalizeExternalUrl("JavaScript:alert(1)")).toBeNull();
+ expect(normalizeExternalUrl(" javascript:alert(1)")).toBeNull();
+ expect(normalizeExternalUrl("data:text/html,<script>alert(1)</script>")).toBeNull();
+ expect(normalizeExternalUrl("vbscript:msgbox(1)")).toBeNull();
+ });
+
+ it("rejects a value that is no address at all", () => {
+ expect(normalizeExternalUrl(undefined)).toBeNull();
+ expect(normalizeExternalUrl(null)).toBeNull();
+ expect(normalizeExternalUrl(" ")).toBeNull();
+ });
+});
+
+describe("safeUrlHref", () => {
+ it("links what may be followed and renders the rest inert, rather than leaving it out", () => {
+ expect(safeUrlHref("example.com")).toBe("https://example.com");
+ expect(safeUrlHref("https://example.com")).toBe("https://example.com");
+ expect(safeUrlHref("javascript:alert(1)")).toBe("about:blank");
+ });
+
+ it("renders a blank href for missing values, an empty cell being no link", () => {
+ expect(safeUrlHref(undefined)).toBe("");
+ expect(safeUrlHref(null)).toBe("");
+ expect(safeUrlHref(" ")).toBe("");
+ });
+});
diff --git a/apps/client/src/utils/url.ts b/apps/client/src/utils/url.ts
new file mode 100644
index 0000000000..a6d093c6b2
--- /dev/null
+++ b/apps/client/src/utils/url.ts
@@ -0,0 +1,29 @@
+import { isHttpUrl } from "@triliumnext/commons";
+
+/**
+ * A url-typed label value as the address it may be followed to, or `null` where it is not one we may
+ * follow at all.
+ *
+ * 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 rejected rather than opened. A value carrying no scheme gets the
+ * `https://` an address bar would give it, rather than being followed as a path relative to Trilium
+ * itself.
+ */
+export function normalizeExternalUrl(value: unknown): string | null {
+ if (typeof value !== "string" || !value.trim()) return null;
+
+ const trimmed = value.trim();
+ const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`;
+ return isHttpUrl(withScheme) ? withScheme : null;
+}
+
+/**
+ * The `href` to link a url-typed label value as. A value we may not follow is rendered inert rather
+ * than left out, so that what a note holds stays readable — as the share view and the markdown export
+ * already do with a hostile scheme. See {@link normalizeExternalUrl}.
+ */
+export function safeUrlHref(value: unknown): string {
+ if (typeof value !== "string" || !value.trim()) return "";
+
+ return normalizeExternalUrl(value) ?? "about:blank";
+}
diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx
index 14d3852909..115f2ff963 100644
--- a/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx
+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx
@@ -369,6 +369,24 @@ describe("LabelValueInput", () => {
}
});
+ it("opens a url only where its scheme is one that may be followed", async () => {
+ const open = vi.spyOn(window, "open").mockImplementation(() => null);
+ try {
+ // A bare address would otherwise be opened relative to Trilium's own origin.
+ await mount({ labelType: "url", value: "example.com/docs", onCommit: vi.fn() });
+ await act(async () => container.querySelector<HTMLElement>(".open-external-link-button")?.click());
+ expect(open).toHaveBeenLastCalledWith("https://example.com/docs", "_blank");
+
+ // Whereas a scheme that would run in Trilium's origin opens nothing at all.
+ await mount({ labelType: "url", value: "javascript:alert(1)", onCommit: vi.fn() });
+ open.mockClear();
+ await act(async () => container.querySelector<HTMLElement>(".open-external-link-button")?.click());
+ expect(open).not.toHaveBeenCalled();
+ } finally {
+ open.mockRestore();
+ }
+ });
+
it("maps every label type to a field, colour included", () => {
// Guards the mapping against a type being added to the vocabulary without a field to edit it.
expect(Object.keys(LABEL_MAPPINGS).length).toBeGreaterThan(0);
diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
index f4428a1152..59f1359b85 100644
--- a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
@@ -6,6 +6,7 @@ import { createElement, type HTMLInputTypeAttribute, type InputHTMLAttributes, t
import { useRef } from "preact/hooks";
import { t } from "../../services/i18n";
+import { normalizeExternalUrl } from "../../utils/url";
import { SelectComboBox } from "./select_input";
/**
@@ -41,13 +42,15 @@ export const DEFAULT_COLOR = "#ffffff";
const OPEN_BUTTONS: Partial<Record<LabelType, {
icon: string;
title: () => string;
- /** Builds the href to open from the bare stored value. */
- toHref: (value: string) => string;
+ /** Builds the href to open from the bare stored value, or `null` for one that may not be opened. */
+ toHref: (value: string) => string | null;
}>> = {
url: {
icon: "bx bx-window-open",
title: () => t("promoted_attributes.open_external_link"),
- toHref: (value) => value
+ // A stored value is free text, so the button opens only what may be followed as an address —
+ // never a `javascript:` scheme, which would otherwise run in Trilium's own origin.
+ toHref: normalizeExternalUrl
},
email: {
icon: "bx bx-envelope",
@@ -219,8 +222,9 @@ export default function LabelValueInput({
title={openButton.title()}
onClick={() => {
const target = inputRef.current?.value || value;
- if (target) {
- window.open(openButton.toHref(target), "_blank");
+ const href = target ? openButton.toHref(target) : null;
+ if (href) {
+ window.open(href, "_blank");
}
}}
/>
diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.ts
index a6fad15ec0..7653a60969 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, safeUrlHref, type ValuesEditorParams } from "./columns";
+import { type AttributeDefinitionInformation, buildColumnDefinitions, formatLabelDate, restoreExistingData, type ValuesEditorParams } from "./columns";
import type { CellComponent, ColumnDefinition } from "tabulator-tables";
import options from "../../../services/options";
@@ -420,31 +420,6 @@ 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.tsx
index d6570df934..79b7209556 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, safeLinkPreviewHref } from "@triliumnext/commons";
+import { LabelType } from "@triliumnext/commons";
import clsx from "clsx";
import { JSX } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
@@ -9,6 +9,7 @@ import type { CellComponent, ColumnDefinition, EmptyCallback, FormatterParams, R
import froca from "../../../services/froca.js";
import { t } from "../../../services/i18n.js";
import { formatDateNumeric } from "../../../utils/formatters.js";
+import { safeUrlHref } from "../../../utils/url.js";
import LabelValueInput from "../../attribute_widgets/label_value_input.jsx";
import { SelectValuesInput } from "../../attribute_widgets/select_input.jsx";
import ValuesInput from "../../attribute_widgets/values_input.jsx";
@@ -110,19 +111,6 @@ 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.