Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/safe-link-schemes.md
Original file line number Diff line number Diff line change
@@ -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.
24 changes: 24 additions & 0 deletions e2e/rich-links.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}) => {
Expand Down
6 changes: 5 additions & 1 deletion src/components/open-url.ts
Original file line number Diff line number Diff line change
@@ -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();
Expand Down
18 changes: 18 additions & 0 deletions src/data/links.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
hasLink,
isHttpUrl,
linkUrlAtOffset,
safeLinkHref,
sanitizeLinkLabel,
stripLinks,
swapLinkLabel,
Expand Down Expand Up @@ -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,<script>alert(1)</script>", null],
["vbscript:msgbox(1)", null],
["", null],
])("safeLinkHref(%p) -> %p", (url, expected) => {
expect(safeLinkHref(url)).toBe(expected);
});
20 changes: 20 additions & 0 deletions src/data/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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). */
Expand Down
6 changes: 6 additions & 0 deletions src/data/opml-export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ test.each<[string, string, string[], string[]?]>([
"&lt;a href=&quot;https://e.com&quot;&gt;l&lt;/a&gt;",
],
],
[
"a javascript: link exports as its label with no anchor",
"[x](javascript:alert%281%29) [y](JaVaScRiPt:alert%281%29)",
['text="x y"'],
["&lt;a", "javascript", "JaVaScRiPt"],
],
[
"the underscore italic alias exports like *i*",
"_i_",
Expand Down
6 changes: 4 additions & 2 deletions src/data/opml-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -204,7 +204,9 @@ function tokenToHtml(
if (tok.startsWith("[")) {
const m = MD_LINK_RE.exec(tok);
if (!m) return escapeHtml(tok);
return `<a href="${escapeHtml(m[2] ?? "")}">${projectText(m[1] ?? "", index, appOrigin, true)}</a>`;
const label = projectText(m[1] ?? "", index, appOrigin, true);
const href = safeLinkHref(m[2] ?? "");
return href ? `<a href="${escapeHtml(href)}">${label}</a>` : label;
}
if (tok.startsWith("==")) {
const { color, interior } = parseHighlight(tok);
Expand Down
12 changes: 12 additions & 0 deletions src/data/opml-import.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,18 @@ test.each<[string, string, string, number]>([
"**[go](https://e.com)**",
0,
],
[
"a javascript: href keeps only its label",
"&lt;a href=&quot;javascript:alert(1)&quot;&gt;go&lt;/a&gt;",
"go",
1,
],
[
"a mixed-case JaVaScRiPt: href keeps only its label",
"&lt;a href=&quot; JaVaScRiPt:alert(1)&quot;&gt;go&lt;/a&gt;",
"go",
1,
],
[
"redundant italic nesting stays italic",
"&lt;i&gt;&lt;i&gt;x&lt;/i&gt;&lt;/i&gt;",
Expand Down
10 changes: 8 additions & 2 deletions src/data/opml-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 -----------------------------------------------------------
Expand Down Expand Up @@ -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(
Expand Down
175 changes: 11 additions & 164 deletions src/plugins/links/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <img> 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 <a>, 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
Expand Down Expand Up @@ -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<HTMLElement>(".node-text");
openUrlInFocusedTab(href, {
restoreFocus: () => textEl?.focus({ preventScroll: true }),
Expand Down
Loading
Loading