diff --git a/web/src/lib/html-sanitize-schema.ts b/web/src/lib/html-sanitize-schema.ts
index f8e0f05cc..75d0e562b 100644
--- a/web/src/lib/html-sanitize-schema.ts
+++ b/web/src/lib/html-sanitize-schema.ts
@@ -1,3 +1,5 @@
+import { isAllowedLinkUrl } from "@/lib/url-policy";
+
const TRUSTED_IFRAME_SRC_PATTERNS = [
/^https:\/\/www\.youtube\.com\/embed\/[^?#]+(?:\?.*)?$/i,
/^https:\/\/www\.youtube-nocookie\.com\/embed\/[^?#]+(?:\?.*)?$/i,
@@ -183,13 +185,12 @@ const CLASS_NAMES: Record = {
};
/**
- * The URL schemes an attribute may use; a relative URL is always allowed. Links also allow
- * `tel:` and `sms:`, which hand off to another app (dialer, messaging) instead of navigating;
- * they cannot run script, so they are as safe as `mailto:`. Sources load over https only.
+ * The URL schemes an attribute may use; a relative URL is always allowed. `href` follows
+ * memos' link policy (`isAllowedLinkUrl`) instead of a fixed list, since a custom scheme
+ * hands off to another app as `mailto:` does. Sources load over https only.
*/
const URL_PROTOCOLS: Record = {
cite: ["http", "https"],
- href: ["http", "https", "irc", "ircs", "mailto", "xmpp", "tel", "sms"],
longdesc: ["http", "https"],
src: ["https"],
};
@@ -223,6 +224,7 @@ export const allowedAttributeValue = (tag: string, name: string, value: string):
return names.length ? names.join(" ") : null;
}
if (tag === "iframe" && name === "src") return isTrustedIframeSrc(value) ? value : null;
+ if (name === "href") return isAllowedLinkUrl(value) ? value : null;
const protocols = URL_PROTOCOLS[name];
return protocols && !hasAllowedProtocol(value.trim(), protocols) ? null : value;
};
diff --git a/web/src/lib/memo-markdown.ts b/web/src/lib/memo-markdown.ts
index ecd6f2360..d35b471dd 100644
--- a/web/src/lib/memo-markdown.ts
+++ b/web/src/lib/memo-markdown.ts
@@ -1,7 +1,6 @@
import {
type Block,
type Doc,
- defaultResolveUrl,
type Extension,
footnotes,
isPlainTextBlock,
@@ -26,6 +25,7 @@ import { colorToHex } from "@/lib/color";
import { headingClasses, markdownStyles, mentionStyles, tagStyles } from "@/lib/markdownStyles";
import { MEMO_MARKDOWN, MEMO_SYNTAX } from "@/lib/memo-ast";
import { findTagMetadata } from "@/lib/tag";
+import { isAllowedLinkUrl } from "@/lib/url-policy";
import { cn } from "@/lib/utils";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
@@ -213,8 +213,8 @@ const isAllowedImageSource = (src: string): boolean => !/^[a-z][a-z0-9+.-]*:/i.t
/**
* memos' URL policy: images the memo names load from relative or https URLs only, and
* managed attachment images then resolve to their served URL, which is the instance's
- * own origin and may be plain http. Links also allow `sms:`, which hands off to another
- * app, beyond the editor's defaults.
+ * own origin and may be plain http. Links follow memos' link policy, which keeps a custom
+ * scheme such as `obsidian://` or `slack://` and drops the ones that run script.
*/
export const memoResolveUrl =
(attachments: readonly Attachment[] = []): ResolveUrl =>
@@ -222,7 +222,7 @@ export const memoResolveUrl =
if (kind === "image") {
return isAllowedImageSource(url) ? (resolveManagedAttachmentImageSource(url, [...attachments]) ?? url) : null;
}
- return /^sms:/i.test(url.trim()) ? url.trim() : defaultResolveUrl(url, kind);
+ return isAllowedLinkUrl(url.trim()) ? url.trim() : null;
};
/**
diff --git a/web/src/lib/sanitized-html.ts b/web/src/lib/sanitized-html.ts
index 3c1b0fbac..790fe2377 100644
--- a/web/src/lib/sanitized-html.ts
+++ b/web/src/lib/sanitized-html.ts
@@ -82,7 +82,9 @@ export function sanitizeMemoHtml(tree: DocumentFragment): DocumentFragment {
// DOMPurify sanitizes an element in place, not a fragment, so the tree goes into one for the pass.
const root = (tree.ownerDocument ?? document).createElement("div");
root.append(tree);
- purify.sanitize(root, { ALLOWED_TAGS, ALLOWED_ATTR: ALLOWED_ATTRIBUTES, IN_PLACE: true });
+ // Unknown schemes reach `allowedAttributeValue`, which holds memos' URL policy and refuses
+ // the script-capable ones, so a custom URI such as `obsidian://` keeps its `href`.
+ purify.sanitize(root, { ALLOWED_TAGS, ALLOWED_ATTR: ALLOWED_ATTRIBUTES, IN_PLACE: true, ALLOW_UNKNOWN_PROTOCOLS: true });
for (const element of Array.from(root.querySelectorAll("*"))) {
if (!finishElement(element)) element.remove();
}
diff --git a/web/src/lib/url-policy.ts b/web/src/lib/url-policy.ts
new file mode 100644
index 000000000..58f54ab9d
--- /dev/null
+++ b/web/src/lib/url-policy.ts
@@ -0,0 +1,26 @@
+/** Schemes that can execute scripts or load active content. */
+const SCRIPT_CAPABLE_SCHEMES = new Set(["javascript", "data", "vbscript", "livescript", "mocha"]);
+
+/** The leading controls and spaces a browser strips from a URL before it reads the scheme. */
+const stripLeadingControls = (url: string): string => {
+ let start = 0;
+ while (start < url.length && url.charCodeAt(start) <= 0x20) start += 1;
+ return url.slice(start);
+};
+
+/** A URL's scheme in lower case, or undefined when it has none: `#anchor`, `/path`, `path?q=1`. */
+const schemeOf = (url: string): string | undefined => {
+ // A browser reads a scheme past the controls it strips from a URL, so the check does too.
+ const value = stripLeadingControls(url).replace(/[\t\n\r]/g, "");
+ const colon = value.indexOf(":");
+ if (colon === -1) return undefined;
+ // The first separator after the colon starts the path, query or fragment; a colon past it is not a scheme.
+ const separator = Math.min(...["/", "?", "#"].map((character) => value.indexOf(character)).filter((index) => index !== -1));
+ return Number.isFinite(separator) && colon > separator ? undefined : value.slice(0, colon).toLowerCase();
+};
+
+/** Whether a link may use `url`: it has no scheme, or a scheme that cannot run script. */
+export const isAllowedLinkUrl = (url: string): boolean => {
+ const scheme = schemeOf(url.trim());
+ return scheme === undefined || !SCRIPT_CAPABLE_SCHEMES.has(scheme);
+};
diff --git a/web/tests/memo-content-security.test.ts b/web/tests/memo-content-security.test.ts
index 09dace97a..250aba30b 100644
--- a/web/tests/memo-content-security.test.ts
+++ b/web/tests/memo-content-security.test.ts
@@ -132,6 +132,50 @@ describe("trusted iframe providers", () => {
});
});
+describe("link URL policy", () => {
+ const resolve = memoResolveUrl();
+
+ it("keeps links to web pages and to other apps, and drops the script-capable schemes", () => {
+ expect(resolve("/notes", "link")).toBe("/notes");
+ expect(resolve("https://example.com/a", "link")).toBe("https://example.com/a");
+ expect(resolve("obsidian://open?vault=notes", "link")).toBe("obsidian://open?vault=notes");
+ expect(resolve("slack://channel?team=T123", "link")).toBe("slack://channel?team=T123");
+ expect(resolve("sms:+44", "link")).toBe("sms:+44");
+ expect(resolve("javascript:alert(1)", "link")).toBeNull();
+ expect(resolve("JaVaScRiPt:alert(1)", "link")).toBeNull();
+ expect(resolve("java\tscript:alert(1)", "link")).toBeNull();
+ expect(resolve("java\nscript:alert(1)", "link")).toBeNull();
+ expect(resolve("\u0001javascript:alert(1)", "link")).toBeNull();
+ expect(resolve("data:text/html,", "link")).toBeNull();
+ });
+
+ it.each([
+ "javascript:alert(1)",
+ "JaVaScRiPt:alert(1)",
+ "java\tscript:alert(1)",
+ "java\nscript:alert(1)",
+ "\u0001javascript:alert(1)",
+ "data:text/html,x",
+ "vbscript:msgbox(1)",
+ "livescript:alert(1)",
+ "mocha:alert(1)",
+ ])("strips unsafe raw HTML link targets: %s", (url) => {
+ const element = document.createElement("a");
+ element.setAttribute("href", url);
+ element.textContent = "unsafe";
+ const tree = document.createDocumentFragment();
+ tree.append(element);
+ const sanitized = sanitizeMemoHtml(tree);
+ expect(sanitized.querySelector("a")?.hasAttribute("href")).toBe(false);
+ expect(resolve(url, "link")).toBeNull();
+ });
+
+ it("keeps a custom-scheme anchor's href in raw HTML", () => {
+ expect(renderHtml('notes
')).toContain('href="obsidian://open?vault=notes"');
+ expect(renderHtml('x
')).not.toContain("javascript:");
+ });
+});
+
describe("image URL policy", () => {
const resolve = memoResolveUrl([create(AttachmentSchema, { name: "attachments/photo", filename: "photo.png", type: "image/png" })]);
@@ -140,6 +184,8 @@ describe("image URL policy", () => {
expect(resolve("https://img.example/a.png", "image")).toBe("https://img.example/a.png");
expect(resolve("http://tracker.example/a.png", "image")).toBeNull();
expect(resolve("javascript:alert(1)", "image")).toBeNull();
+ expect(resolve("obsidian://open?vault=notes", "image")).toBeNull();
+ expect(renderHtml('
')).not.toContain("obsidian:");
});
it("resolves a managed attachment image to the instance's own URL, even over plain http", () => {
diff --git a/web/tests/memo-content-view.test.tsx b/web/tests/memo-content-view.test.tsx
index 69096fd35..80b33dc53 100644
--- a/web/tests/memo-content-view.test.tsx
+++ b/web/tests/memo-content-view.test.tsx
@@ -354,6 +354,12 @@ describe("links", () => {
expect(open).not.toHaveBeenCalled();
expect(container.querySelector('a[href="sms:+44"]')).not.toBeNull();
});
+
+ it("keeps a link whose scheme hands off to another app", () => {
+ const { container } = renderMemo("[vault](obsidian://open?vault=notes) [channel](slack://channel?team=T123)");
+ expect(container.querySelector('a[href="obsidian://open?vault=notes"]')).not.toBeNull();
+ expect(container.querySelector('a[href="slack://channel?team=T123"]')).not.toBeNull();
+ });
});
describe("images", () => {
diff --git a/web/tests/memo-editor-link-paste.test.ts b/web/tests/memo-editor-link-paste.test.ts
new file mode 100644
index 000000000..c61da7d00
--- /dev/null
+++ b/web/tests/memo-editor-link-paste.test.ts
@@ -0,0 +1,85 @@
+import { commands, Editor } from "@usememos/editor";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { buildEditorExtensions } from "@/components/MemoEditor/edit/extensions";
+import { memoResolveUrl } from "@/lib/memo-markdown";
+
+const editors: Editor[] = [];
+
+afterEach(() => {
+ editors.splice(0).forEach((e) => e.destroy());
+ document.body.replaceChildren();
+});
+
+function setup(content = "") {
+ const root = document.createElement("div");
+ document.body.append(root);
+ const extensions = buildEditorExtensions({ getTags: () => [], onFiles: vi.fn(), emojiLabel: "Emoji" });
+ const editor = new Editor({ element: root, content, resolveUrl: memoResolveUrl(), extensions });
+ editors.push(editor);
+ editor.focus();
+ return { editor, root };
+}
+
+function paste(root: HTMLElement, text: string, plain = false) {
+ if (plain) root.dispatchEvent(new KeyboardEvent("keydown", { key: "v", ctrlKey: true, metaKey: true, shiftKey: true, bubbles: true }));
+ const event = new Event("paste", { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "clipboardData", {
+ value: { files: [], types: ["text/plain"], getData: (type: string) => (type === "text/plain" ? text : "") },
+ });
+ root.dispatchEvent(event);
+}
+
+describe("memo editor link paste", () => {
+ it("links a custom URI at the caret without losing punctuation", () => {
+ const { root } = setup();
+ paste(root, "obsidian://open?x=a)b]");
+ expect(root.querySelector("a")?.getAttribute("href")).toBe("obsidian://open?x=a)b]");
+ });
+
+ it("links selected text", () => {
+ const { root, editor } = setup("notes");
+ editor.setSelection({ anchor: { block: 0, offset: 0 }, focus: { block: 0, offset: 5 } });
+ paste(root, "slack://channel?team=T123");
+ expect(root.querySelector("a")?.getAttribute("href")).toBe("slack://channel?team=T123");
+ expect(root.textContent).toBe("notes");
+ });
+
+ it("keeps plain-text paste literal", () => {
+ const { root } = setup();
+ paste(root, "obsidian://open?vault=x", true);
+ expect(root.querySelector("a")).toBeNull();
+ expect(root.textContent).toBe("obsidian://open?vault=x");
+ });
+
+ it("replaces a code-to-prose selection on plain-text paste", () => {
+ const { root, editor } = setup("```\nliteral\n```\n\nwords");
+ editor.setSelection({ anchor: { block: 0, offset: 0 }, focus: { block: 1, offset: 5 } });
+ paste(root, "obsidian://open?vault=x", true);
+ expect(root.textContent).not.toContain("literal");
+ expect(root.textContent).not.toContain("words");
+ expect(root.querySelector("a")).toBeNull();
+ expect(root.textContent).toContain("obsidian://open?vault=x");
+ });
+
+ it("keeps a code-block paste literal", () => {
+ const { root, editor } = setup("```\nliteral\n```");
+ editor.setSelection({ anchor: { block: 0, offset: 7 }, focus: { block: 0, offset: 7 } });
+ paste(root, "obsidian://open?vault=x");
+ expect(root.querySelector("a")).toBeNull();
+ expect(root.textContent).toContain("literalobsidian://open?vault=x");
+ });
+
+ it("allows manually linking selected text to another app", () => {
+ const { root, editor } = setup("notes");
+ editor.setSelection({ anchor: { block: 0, offset: 0 }, focus: { block: 0, offset: 5 } });
+ editor.run((state) => commands.setLink(state, "obsidian://open?vault=notes"));
+ expect(root.querySelector("a")?.getAttribute("href")).toBe("obsidian://open?vault=notes");
+ expect(root.textContent).toBe("notes");
+ });
+
+ it("drops dangerous link schemes", () => {
+ const { root } = setup();
+ paste(root, "javascript://alert(1)");
+ expect(root.querySelector("a")).toBeNull();
+ });
+});