diff --git a/.changeset/safe-link-schemes.md b/.changeset/safe-link-schemes.md
new file mode 100644
index 00000000..6383f03b
--- /dev/null
+++ b/.changeset/safe-link-schemes.md
@@ -0,0 +1,5 @@
+---
+"dotflowy": patch
+---
+
+Links only open when they use http, https, or mailto. A `javascript:` or other script link, whether typed, pasted, or imported from OPML, now shows as inert text.
diff --git a/e2e/rich-links.spec.ts b/e2e/rich-links.spec.ts
index 66fccd68..fe99dcae 100644
--- a/e2e/rich-links.spec.ts
+++ b/e2e/rich-links.spec.ts
@@ -451,6 +451,30 @@ test("clicking a folded link opens it in a new tab and does NOT reveal/edit", as
await expect(text(page, "n").locator(".link-reveal")).toBeVisible();
});
+test("a javascript: link folds without an href and never opens", async ({
+ page,
+}) => {
+ await load(page, [
+ {
+ id: "n",
+ parentId: null,
+ prevSiblingId: null,
+ text: "[x](JaVaScRiPt:alert%281%29)",
+ },
+ ]);
+
+ const anchor = text(page, "n").locator("a[data-link]");
+ await expect(anchor).toHaveAttribute("data-unsafe-link", "");
+ await expect(anchor).not.toHaveAttribute("href", /.*/);
+ await anchor.click();
+ expect(await opened(page)).toEqual([]);
+
+ await focusBullet(page, "n");
+ await placeCaret(text(page, "n").locator(".link-label"), 1);
+ await page.keyboard.press("ControlOrMeta+Enter");
+ expect(await opened(page)).toEqual([]);
+});
+
test("Mod+Enter inside a markdown link opens it instead of completing the node", async ({
page,
}) => {
diff --git a/src/components/open-url.ts b/src/components/open-url.ts
index bc4f16e3..d780d26e 100644
--- a/src/components/open-url.ts
+++ b/src/components/open-url.ts
@@ -1,8 +1,12 @@
+import { safeLinkHref } from "../data/links";
+
export function openUrlInFocusedTab(
url: string,
options: { restoreFocus?: () => void } = {},
): void {
- const tab = window.open(url, "_blank");
+ const href = safeLinkHref(url);
+ if (!href) return; // javascript:, data:, ... never open
+ const tab = window.open(href, "_blank");
if (!tab) return; // popup blocked -- nothing opened, nothing to restore
if (options.restoreFocus) restoreOnReturn(options.restoreFocus);
tab.focus();
diff --git a/src/data/links.test.ts b/src/data/links.test.ts
index 90b03fe1..d3ed78ff 100644
--- a/src/data/links.test.ts
+++ b/src/data/links.test.ts
@@ -6,6 +6,7 @@ import {
hasLink,
isHttpUrl,
linkUrlAtOffset,
+ safeLinkHref,
sanitizeLinkLabel,
stripLinks,
swapLinkLabel,
@@ -104,3 +105,20 @@ test("swapLinkLabel matches against the ENCODED url half (parens case)", () => {
`[Foo (bar)](${enc}) tail`,
);
});
+
+test.each([
+ ["https://e.com/a?b=1", "https://e.com/a?b=1"],
+ ["HTTP://E.COM", "HTTP://E.COM"],
+ ["mailto:a@e.com", "mailto:a@e.com"],
+ ["/relative/path", "/relative/path"],
+ ["javascript:alert(1)", null],
+ ["JaVaScRiPt:alert(1)", null],
+ [" javascript:alert(1)", null],
+ ["java\tscript:alert(1)", null],
+ ["java\nscript:alert(1)", null],
+ ["data:text/html,", null],
+ ["vbscript:msgbox(1)", null],
+ ["", null],
+])("safeLinkHref(%p) -> %p", (url, expected) => {
+ expect(safeLinkHref(url)).toBe(expected);
+});
diff --git a/src/data/links.ts b/src/data/links.ts
index e278d86e..6fcfac94 100644
--- a/src/data/links.ts
+++ b/src/data/links.ts
@@ -67,6 +67,26 @@ export function isHttpUrl(s: string): boolean {
return /^https?:\/\//i.test(s.trim());
}
+const SAFE_LINK_PROTOCOLS = new Set(["http:", "https:", "mailto:"]);
+// Relative urls resolve against the page's own http(s) origin, so parse them
+// against a placeholder https base; only the scheme of the result matters.
+const RELATIVE_LINK_BASE = "https://dotflowy.invalid/";
+
+/** The url when it is safe to use as an `href` or to open, else null. Parses
+ * with the WHATWG URL parser (the same one the browser applies to `href`), so
+ * mixed case, leading whitespace, and embedded tabs/newlines can't sneak a
+ * `javascript:` or `data:` scheme past the http/https/mailto allowlist. */
+export function safeLinkHref(url: string): string | null {
+ const trimmed = url.trim();
+ if (!trimmed) return null;
+ try {
+ const { protocol } = new URL(trimmed, RELATIVE_LINK_BASE);
+ return SAFE_LINK_PROTOCOLS.has(protocol) ? trimmed : null;
+ } catch {
+ return null;
+ }
+}
+
/** If `s` is exactly one bare http(s) URL (no surrounding whitespace/words),
* return it trimmed; otherwise null. Used by paste (wrap a selection, or
* auto-link a pasted URL). */
diff --git a/src/data/opml-export.test.ts b/src/data/opml-export.test.ts
index aec25606..7dcd5bbd 100644
--- a/src/data/opml-export.test.ts
+++ b/src/data/opml-export.test.ts
@@ -143,6 +143,12 @@ test.each<[string, string, string[], string[]?]>([
"<a href="https://e.com">l</a>",
],
],
+ [
+ "a javascript: link exports as its label with no anchor",
+ "[x](javascript:alert%281%29) [y](JaVaScRiPt:alert%281%29)",
+ ['text="x y"'],
+ ["<a", "javascript", "JaVaScRiPt"],
+ ],
[
"the underscore italic alias exports like *i*",
"_i_",
diff --git a/src/data/opml-export.ts b/src/data/opml-export.ts
index 30b05e24..3a4c82b2 100644
--- a/src/data/opml-export.ts
+++ b/src/data/opml-export.ts
@@ -24,7 +24,7 @@ import {
parseHighlight,
type HighlightColor,
} from "./highlight";
-import { LINK_PATTERN, sanitizeLinkLabel } from "./links";
+import { LINK_PATTERN, safeLinkHref, sanitizeLinkLabel } from "./links";
import { NODE_LINK_PATTERN, linkTargetId, linkedNodeLabel } from "./node-links";
import { childrenOf, trueSourceOf, type TreeIndex } from "./tree";
@@ -204,7 +204,9 @@ function tokenToHtml(
if (tok.startsWith("[")) {
const m = MD_LINK_RE.exec(tok);
if (!m) return escapeHtml(tok);
- return `${projectText(m[1] ?? "", index, appOrigin, true)}`;
+ const label = projectText(m[1] ?? "", index, appOrigin, true);
+ const href = safeLinkHref(m[2] ?? "");
+ return href ? `${label}` : label;
}
if (tok.startsWith("==")) {
const { color, interior } = parseHighlight(tok);
diff --git a/src/data/opml-import.test.ts b/src/data/opml-import.test.ts
index 51408b7e..58c70046 100644
--- a/src/data/opml-import.test.ts
+++ b/src/data/opml-import.test.ts
@@ -174,6 +174,18 @@ test.each<[string, string, string, number]>([
"**[go](https://e.com)**",
0,
],
+ [
+ "a javascript: href keeps only its label",
+ "<a href="javascript:alert(1)">go</a>",
+ "go",
+ 1,
+ ],
+ [
+ "a mixed-case JaVaScRiPt: href keeps only its label",
+ "<a href=" JaVaScRiPt:alert(1)">go</a>",
+ "go",
+ 1,
+ ],
[
"redundant italic nesting stays italic",
"<i><i>x</i></i>",
diff --git a/src/data/opml-import.ts b/src/data/opml-import.ts
index 1d06ba69..b63f62d1 100644
--- a/src/data/opml-import.ts
+++ b/src/data/opml-import.ts
@@ -23,7 +23,7 @@ import type { ChangeOp } from "./wire-schema";
import { isValidDateKey } from "./date-links";
import { emphasisAt } from "./emphasis";
import { buildHighlightRun, type HighlightColor } from "./highlight";
-import { encodeUrlForMarkdown, sanitizeLinkLabel } from "./links";
+import { encodeUrlForMarkdown, safeLinkHref, sanitizeLinkLabel } from "./links";
import { createNode, type NodeKind } from "./tree";
// --- Typed failures -----------------------------------------------------------
@@ -388,7 +388,13 @@ function convertEl(
return convert(el.children, state);
}
const rawLabel = convert(el.children, { ...state, insideLink: true });
- const url = encodeUrlForMarkdown(el.attrs["href"] ?? "");
+ const href = safeLinkHref(el.attrs["href"] ?? "");
+ if (!href) {
+ if (el.attrs["href"]?.trim())
+ degraded.bump("unsafe link href dropped (label kept)");
+ return rawLabel;
+ }
+ const url = encodeUrlForMarkdown(href);
const label = sanitizeLinkLabel(rawLabel);
if (label !== rawLabel.trim() || rawLabel.includes("]")) {
degraded.bump(
diff --git a/src/plugins/links/index.ts b/src/plugins/links/index.ts
index 5adf1a85..f0ec1827 100644
--- a/src/plugins/links/index.ts
+++ b/src/plugins/links/index.ts
@@ -22,178 +22,24 @@ import {
encodeUrlForMarkdown,
isHttpUrl,
LINK_PATTERN,
+ safeLinkHref,
} from "../../data/links";
import { getTreeIndex } from "../../data/tree-store";
-import { isRevealed, mdPunct, resolveNodeId } from "../token-kit";
-import {
- definePlugin,
- type El,
- type PluginContext,
- type TokenView,
- type WidgetEl,
-} from "../types";
+import { isRevealed, resolveNodeId } from "../token-kit";
+import { definePlugin, type PluginContext } from "../types";
import { LINK_FILTER_OPERATORS } from "./filter-operators";
import {
openLinkCreatePopover,
openLinkEditPopover,
} from "./link-edit-popover";
+import {
+ editButtonEl,
+ foldedLinkEl,
+ LINK_PARTS,
+ revealedLinkEl,
+} from "./render";
import { unfurlNodeLinks } from "./unfurl";
-// Pull `[label](url)` apart for rendering. Mirrors the combined-regex shape, so
-// it always matches what the tokenizer fed us.
-const LINK_PARTS = /^\[([^\]]*)\]\(([^)]*)\)$/;
-
-const LINK_CLASS = "node-link cursor-pointer";
-
-// The host of a folded link's url, for the favicon lookup -- or null if the url
-// won't parse (a hand-typed rough edge). The token's url is percent-encoded for
-// `( ) space` only, so `new URL` parses the scheme + host fine.
-function linkHost(url: string): string | null {
- try {
- return new URL(url).hostname || null;
- } catch {
- return null;
- }
-}
-
-// The site's favicon, served by Google's long-lived s2/favicons endpoint, which
-// falls back to a generic glyph on a miss -- so the
never shows a broken-
-// image icon. Chosen over smaller services for longevity (it renders on every
-// link, forever). `sz=64` stays crisp on hi-dpi at the small render box. It
-// rides INSIDE the folded , so a click on it opens the link like any other
-// part of the anchor, and `loading="lazy"` keeps offscreen links cheap.
-function faviconImgEl(host: string): El {
- return {
- tag: "img",
- attrs: {
- class: "link-favicon",
- src: `https://www.google.com/s2/favicons?domain=${host}&sz=64`,
- alt: "",
- "aria-hidden": "true",
- draggable: "false",
- loading: "lazy",
- },
- };
-}
-
-// A text-free icon, painted by CSS mask inside the accessible pencil button.
-function editIconEl(): El {
- return {
- tag: "span",
- attrs: { class: "link-edit-icon", "aria-hidden": "true" },
- };
-}
-
-function editButtonEl(token?: string): El {
- return {
- tag: "button",
- attrs: {
- type: "button",
- class: "link-edit-button",
- "aria-label": "Edit link",
- title: "Edit link",
- contenteditable: "false",
- "data-src": "",
- "data-src-len": 0,
- "data-link-token": token,
- },
- children: [editIconEl()],
- };
-}
-
-// The wrapper is one source atom. The anchor visits the URL and the sibling
-// pencil edits it, without nesting interactive controls inside the anchor.
-// Plain URLs use the same wrapper without a favicon or metadata lookup.
-function foldedLinkEl(
- label: string,
- url: string,
- tok: string,
- plain = false,
- labelElements: (El | WidgetEl)[] = [label],
-): El {
- const host = plain ? null : linkHost(url);
- const start = label.match(/^\s*\S/u)?.[0] ?? label;
- return {
- tag: "span",
- attrs: {
- class: "link-with-editor",
- contenteditable: "false",
- "data-src": tok,
- "data-src-len": tok.length,
- },
- children: [
- {
- tag: "a",
- attrs: {
- class: LINK_CLASS,
- "data-link": !plain,
- "data-plain-url": plain,
- contenteditable: "false",
- "data-src": tok,
- "data-src-len": tok.length,
- href: url,
- target: "_blank",
- rel: "noopener noreferrer",
- },
- children:
- host && labelElements.length > 1
- ? [faviconImgEl(host), ...labelElements]
- : host
- ? [
- {
- tag: "span",
- attrs: { class: "link-start" },
- children: [faviconImgEl(host), start],
- },
- label.slice(start.length),
- ]
- : labelElements,
- },
- editButtonEl(),
- ],
- };
-}
-
-// A revealed link (bracket reveal, ADR 0005): `[label]` as editable text -- the
-// brackets appear so the label edits as raw markdown -- but the URL itself
-// NEVER expands into the line. Only the bare `url` folds to one atomic chip
-// (`data-src` carries it, so readSource still reconstructs the full token and
-// the caret jumps over it) rendered as a pencil; the parens around it are REAL
-// text, so the caret walks through `](` and `)` one step at a time, and typing
-// between `]` and `(` breaks the token match -- the link splits open to raw
-// text. Clicking the chip opens the Edit Link popover. Everything except the
-// chip stays 1:1 with its slice of the source.
-function revealedLinkEl(label: string, url: string, view: TokenView): El {
- return {
- tag: "span",
- attrs: { class: "link-reveal", "data-link-reveal": true },
- children: [
- mdPunct("["),
- {
- tag: "span",
- attrs: { class: "link-label" },
- children: view.renderInline(label, view.start + 1, true),
- },
- mdPunct("]"),
- mdPunct("("),
- {
- tag: "button",
- attrs: {
- class: "link-url-chip",
- "data-src": url,
- "data-src-len": url.length,
- contenteditable: "false",
- title: "Edit link",
- type: "button",
- "aria-label": "Edit link",
- },
- children: [editIconEl()],
- },
- mdPunct(")"),
- ],
- };
-}
-
// Resolve a click on an edit affordance to (nodeId, token, pencil rect) and
// open the popover. A folded link's sibling pencil reads the full token off
// the anchor's data-src; the revealed url chip reads its own data-src (the
@@ -430,7 +276,8 @@ export default definePlugin({
e.preventDefault();
e.stopPropagation();
// SAFETY: the selector "a[data-link]" matched, so el is an anchor
- const href = (el as HTMLAnchorElement).href;
+ const href = safeLinkHref((el as HTMLAnchorElement).href);
+ if (!href) return;
const textEl = el.closest(".node-text");
openUrlInFocusedTab(href, {
restoreFocus: () => textEl?.focus({ preventScroll: true }),
diff --git a/src/plugins/links/render.test.ts b/src/plugins/links/render.test.ts
new file mode 100644
index 00000000..98dbb7ed
--- /dev/null
+++ b/src/plugins/links/render.test.ts
@@ -0,0 +1,55 @@
+import { expect, test } from "bun:test";
+
+import type { ElNode, TokenView } from "../types";
+
+import { foldedLinkEl, LINK_PARTS, revealedLinkEl } from "./render";
+
+function render(tok: string, revealed = false): ElNode {
+ const [, label = "", url = ""] = LINK_PARTS.exec(tok) ?? [];
+ const view: TokenView = {
+ revealOffset: revealed ? 1 : null,
+ start: 0,
+ end: tok.length,
+ renderInline: (text) => [text],
+ };
+ // SAFETY: both renders return an element node, never a bare string
+ return (
+ revealed ? revealedLinkEl(label, url, view) : foldedLinkEl(label, url, tok)
+ ) as ElNode;
+}
+
+// Every descriptor in the tree carrying `tag: "a"`.
+function anchors(el: ElNode): ElNode[] {
+ const found: ElNode[] = [];
+ JSON.stringify(el, (_key, value: ElNode) => {
+ if (value?.tag === "a") found.push(value);
+ return value;
+ });
+ return found;
+}
+
+function hrefs(el: ElNode): string[] {
+ return JSON.stringify(el).match(/"href":"[^"]*"/g) ?? [];
+}
+
+const unsafe = ["[x](javascript:alert(1))", "[x](JaVaScRiPt:alert(1))"];
+
+test.each(unsafe)("%s folds to an inert anchor with no href", (tok) => {
+ const el = render(tok);
+ const [a] = anchors(el);
+ expect(a?.attrs?.["href"]).toBeUndefined();
+ expect(a?.attrs?.["data-unsafe-link"]).toBe(true);
+ expect(hrefs(el)).toEqual([]);
+ // Still one source atom, so caret math and the edit pencil keep working.
+ expect(el.attrs?.["data-src"]).toBe(tok);
+});
+
+test.each(unsafe)("%s revealed renders no href", (tok) => {
+ expect(hrefs(render(tok, true))).toEqual([]);
+});
+
+test("an https link keeps its href", () => {
+ const [a] = anchors(render("[x](https://e.com)"));
+ expect(a?.attrs?.["href"]).toBe("https://e.com");
+ expect(a?.attrs?.["data-unsafe-link"]).toBe(false);
+});
diff --git a/src/plugins/links/render.ts b/src/plugins/links/render.ts
new file mode 100644
index 00000000..43f819af
--- /dev/null
+++ b/src/plugins/links/render.ts
@@ -0,0 +1,172 @@
+// Pure El descriptors for the links plugin's two token renders (Seam A): the
+// folded anchor and the bracket-revealed form. DOM-free, so unit tests render
+// them without loading the editor core.
+
+import type { El, TokenView, WidgetEl } from "../types";
+
+import { safeLinkHref } from "../../data/links";
+import { mdPunct } from "../token-kit";
+
+// Pull `[label](url)` apart for rendering. Mirrors the combined-regex shape, so
+// it always matches what the tokenizer fed us.
+export const LINK_PARTS = /^\[([^\]]*)\]\(([^)]*)\)$/;
+
+const LINK_CLASS = "node-link cursor-pointer";
+
+// The host of a folded link's url, for the favicon lookup -- or null if the url
+// won't parse (a hand-typed rough edge). The token's url is percent-encoded for
+// `( ) space` only, so `new URL` parses the scheme + host fine.
+function linkHost(url: string): string | null {
+ try {
+ return new URL(url).hostname || null;
+ } catch {
+ return null;
+ }
+}
+
+// The site's favicon, served by Google's long-lived s2/favicons endpoint, which
+// falls back to a generic glyph on a miss -- so the
never shows a broken-
+// image icon. Chosen over smaller services for longevity (it renders on every
+// link, forever). `sz=64` stays crisp on hi-dpi at the small render box. It
+// rides INSIDE the folded , so a click on it opens the link like any other
+// part of the anchor, and `loading="lazy"` keeps offscreen links cheap.
+function faviconImgEl(host: string): El {
+ return {
+ tag: "img",
+ attrs: {
+ class: "link-favicon",
+ src: `https://www.google.com/s2/favicons?domain=${host}&sz=64`,
+ alt: "",
+ "aria-hidden": "true",
+ draggable: "false",
+ loading: "lazy",
+ },
+ };
+}
+
+// A text-free icon, painted by CSS mask inside the accessible pencil button.
+function editIconEl(): El {
+ return {
+ tag: "span",
+ attrs: { class: "link-edit-icon", "aria-hidden": "true" },
+ };
+}
+
+export function editButtonEl(token?: string): El {
+ return {
+ tag: "button",
+ attrs: {
+ type: "button",
+ class: "link-edit-button",
+ "aria-label": "Edit link",
+ title: "Edit link",
+ contenteditable: "false",
+ "data-src": "",
+ "data-src-len": 0,
+ "data-link-token": token,
+ },
+ children: [editIconEl()],
+ };
+}
+
+// The wrapper is one source atom. The anchor visits the URL and the sibling
+// pencil edits it, without nesting interactive controls inside the anchor.
+// Plain URLs use the same wrapper without a favicon or metadata lookup. A url
+// outside the http/https/mailto allowlist renders as an inert, href-less
+// anchor: the label shows and the pencil still edits it, but nothing opens.
+export function foldedLinkEl(
+ label: string,
+ url: string,
+ tok: string,
+ plain = false,
+ labelElements: (El | WidgetEl)[] = [label],
+): El {
+ const href = safeLinkHref(url);
+ const host = plain || !href ? null : linkHost(url);
+ const start = label.match(/^\s*\S/u)?.[0] ?? label;
+ return {
+ tag: "span",
+ attrs: {
+ class: "link-with-editor",
+ contenteditable: "false",
+ "data-src": tok,
+ "data-src-len": tok.length,
+ },
+ children: [
+ {
+ tag: "a",
+ attrs: {
+ class: LINK_CLASS,
+ "data-link": !plain,
+ "data-plain-url": plain,
+ contenteditable: "false",
+ "data-src": tok,
+ "data-src-len": tok.length,
+ href: href ?? undefined,
+ target: href ? "_blank" : undefined,
+ rel: href ? "noopener noreferrer" : undefined,
+ "data-unsafe-link": !href,
+ title: href ? undefined : "Blocked link: unsupported URL scheme",
+ },
+ children:
+ host && labelElements.length > 1
+ ? [faviconImgEl(host), ...labelElements]
+ : host
+ ? [
+ {
+ tag: "span",
+ attrs: { class: "link-start" },
+ children: [faviconImgEl(host), start],
+ },
+ label.slice(start.length),
+ ]
+ : labelElements,
+ },
+ editButtonEl(),
+ ],
+ };
+}
+
+// A revealed link (bracket reveal, ADR 0005): `[label]` as editable text -- the
+// brackets appear so the label edits as raw markdown -- but the URL itself
+// NEVER expands into the line. Only the bare `url` folds to one atomic chip
+// (`data-src` carries it, so readSource still reconstructs the full token and
+// the caret jumps over it) rendered as a pencil; the parens around it are REAL
+// text, so the caret walks through `](` and `)` one step at a time, and typing
+// between `]` and `(` breaks the token match -- the link splits open to raw
+// text. Clicking the chip opens the Edit Link popover. Everything except the
+// chip stays 1:1 with its slice of the source.
+export function revealedLinkEl(
+ label: string,
+ url: string,
+ view: TokenView,
+): El {
+ return {
+ tag: "span",
+ attrs: { class: "link-reveal", "data-link-reveal": true },
+ children: [
+ mdPunct("["),
+ {
+ tag: "span",
+ attrs: { class: "link-label" },
+ children: view.renderInline(label, view.start + 1, true),
+ },
+ mdPunct("]"),
+ mdPunct("("),
+ {
+ tag: "button",
+ attrs: {
+ class: "link-url-chip",
+ "data-src": url,
+ "data-src-len": url.length,
+ contenteditable: "false",
+ title: "Edit link",
+ type: "button",
+ "aria-label": "Edit link",
+ },
+ children: [editIconEl()],
+ },
+ mdPunct(")"),
+ ],
+ };
+}