Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support network images for document and notebook icons https://github.com/siyuan-note/siyuan/issues/12926

Daniel467945834420
diff --git a/app/src/assets/scss/business/_emojis.scss b/app/src/assets/scss/business/_emojis.scss
index 564e997002..e7a035ddff 100644
--- a/app/src/assets/scss/business/_emojis.scss
+++ b/app/src/assets/scss/business/_emojis.scss
@@ -84,6 +84,24 @@
padding: 0 8px;
}
+ &__link {
+ padding: 16px;
+
+ &-preview {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 112px;
+
+ img {
+ width: 80px;
+ height: 80px;
+ object-fit: contain;
+ border-radius: var(--b3-border-radius);
+ }
+ }
+ }
+
&__content {
display: flex;
flex-wrap: wrap;
diff --git a/app/src/emoji/iconValue.test.ts b/app/src/emoji/iconValue.test.ts
new file mode 100644
index 0000000000..f12e554200
--- /dev/null
+++ b/app/src/emoji/iconValue.test.ts
@@ -0,0 +1,55 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {genEmojiImageHTML, normalizeNetworkIconURL} from "./iconValue";
+
+describe("normalizeNetworkIconURL", () => {
+ it("accepts absolute HTTP(S) links without relying on file extensions", () => {
+ assert.equal(normalizeNetworkIconURL(" https://example.com/icon?id=1#preview "), "https://example.com/icon?id=1#preview");
+ assert.equal(normalizeNetworkIconURL("http://127.0.0.1:8080/icon"), "http://127.0.0.1:8080/icon");
+ assert.equal(normalizeNetworkIconURL("HTTPS://example.com/icon path"), "https://example.com/icon%20path");
+ });
+
+ it("rejects non-HTTP(S), relative, and malformed links", () => {
+ [
+ "",
+ "icon.png",
+ "//example.com/icon.png",
+ "data:image/png;base64,AAAA",
+ "file:///tmp/icon.png",
+ "ftp://example.com/icon.png",
+ "javascript:alert(1)",
+ "https://",
+ ].forEach(item => assert.equal(normalizeNetworkIconURL(item), undefined));
+ });
+});
+
+describe("genEmojiImageHTML", () => {
+ it("renders network, dynamic, and custom image icons", () => {
+ assert.equal(
+ genEmojiImageHTML("https://example.com/icon?id=1&size=2", "icon", true),
+ '<img class="icon" data-src="https://example.com/icon?id=1&amp;size=2" referrerpolicy="no-referrer"/>',
+ );
+ assert.equal(
+ genEmojiImageHTML("api/icon/getDynamicIcon?type=1", "icon"),
+ '<img class="icon" src="api/icon/getDynamicIcon?type=1"/>',
+ );
+ assert.equal(
+ genEmojiImageHTML("folder/icon.png"),
+ '<img class="" src="/emojis/folder/icon.png"/>',
+ );
+ });
+
+ it("does not treat unsupported URL schemes or Emoji codepoints as image sources", () => {
+ assert.equal(genEmojiImageHTML("data:image/png;base64,AAAA"), undefined);
+ assert.equal(genEmojiImageHTML("file:///tmp/icon.png"), undefined);
+ assert.equal(genEmojiImageHTML("1f600"), undefined);
+ });
+
+ it("escapes attribute-breaking network URL content", () => {
+ const html = genEmojiImageHTML('https://example.com/&quot;" onerror="alert(1).png', '" onerror="alert(2)');
+ assert.ok(html);
+ assert.equal((html.match(/\ssrc=/g) || []).length, 1);
+ assert.equal((html.match(/\sonerror="/g) || []).length, 0);
+ assert.match(html, /&amp;quot;%22/);
+ });
+});
diff --git a/app/src/emoji/iconValue.ts b/app/src/emoji/iconValue.ts
new file mode 100644
index 0000000000..a014a34ce1
--- /dev/null
+++ b/app/src/emoji/iconValue.ts
@@ -0,0 +1,42 @@
+import {escapeAttr, escapeHtml} from "../util/escape";
+
+const DYNAMIC_ICON_PREFIX = "api/icon/getDynamicIcon";
+const URL_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z\d+.-]*:/;
+
+export const normalizeNetworkIconURL = (value: string): string | undefined => {
+ const icon = value.trim();
+ let url: URL;
+ try {
+ url = new URL(icon);
+ } catch {
+ return;
+ }
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || !url.host) {
+ return;
+ }
+ return url.href;
+};
+
+export const genEmojiImageHTML = (value: string, className = "", lazy = false): string | undefined => {
+ let src: string;
+ let network = false;
+ if (value.startsWith(DYNAMIC_ICON_PREFIX)) {
+ src = value;
+ } else {
+ const networkURL = normalizeNetworkIconURL(value);
+ if (networkURL) {
+ src = networkURL;
+ network = true;
+ } else if (URL_SCHEME_PATTERN.test(value) || value.startsWith("//")) {
+ return;
+ } else if (value.includes(".")) {
+ src = `/emojis/${value}`;
+ } else {
+ return;
+ }
+ }
+
+ const safeClassName = escapeAttr(escapeHtml(className));
+ const safeSrc = escapeAttr(escapeHtml(src));
+ return `<img class="${safeClassName}" ${lazy ? "data-" : ""}src="${safeSrc}"${network ? ' referrerpolicy="no-referrer"' : ""}/>`;
+};
diff --git a/app/src/emoji/index.ts b/app/src/emoji/index.ts
index 1e5eec68c3..aa761c9061 100644
--- a/app/src/emoji/index.ts
+++ b/app/src/emoji/index.ts
@@ -12,6 +12,8 @@ import {setPosition} from "../util/setPosition";
import {setStorageVal} from "../protyle/util/compatibility";
import {getLuteInstance} from "../protyle/render/setLute";
import * as dayjs from "dayjs";
+import {genEmojiImageHTML, normalizeNetworkIconURL} from "./iconValue";
+import {showMessage} from "../dialog/message";
export const getRandomEmoji = () => {
const emojis = window.siyuan.emojis[getRandom(0, window.siyuan.emojis.length - 1)];
@@ -26,12 +28,9 @@ export const unicode2Emoji = (unicode: string, className = "", needSpan = false,
return "";
}
let emoji = "";
- if (unicode.startsWith("api/icon/getDynamicIcon")) {
- emoji = `<img class="${className}" ${lazy ? "data-" : ""}src="${unicode}"/>`;
- emoji = Lute.Sanitize(emoji);
- } else if (unicode.indexOf(".") > -1) {
- emoji = `<img class="${className}" ${lazy ? "data-" : ""}src="/emojis/${unicode}"/>`;
- emoji = Lute.Sanitize(emoji);
+ const imageHTML = genEmojiImageHTML(unicode, className, lazy);
+ if (imageHTML) {
+ emoji = Lute.Sanitize(imageHTML);
} else {
try {
unicode.split("-").forEach(item => {
@@ -287,6 +286,7 @@ export const openEmojiPanel = (
<div data-type="tab-emoji" class="ariaLabel block__icon block__icon--show" aria-label="${window.siyuan.languages.emoji}"><svg><use xlink:href="#iconEmoji"></use></svg></div>
<div class="fn__space"></div>
<div data-type="tab-dynamic" class="ariaLabel block__icon block__icon--show${options?.dynamic ? " fn__none" : ""}" aria-label="${window.siyuan.languages.dynamicIcon}"><svg><use xlink:href="#iconCalendar"></use></svg></div>
+ <div data-type="tab-link" class="ariaLabel block__icon block__icon--show${type === "av" ? " fn__none" : ""}" aria-label="${window.siyuan.languages.insertImgURL}"><svg><use xlink:href="#iconLink"></use></svg></div>
<div class="fn__flex-1"></div>
<span class="block__icon block__icon--show fn__flex-center ariaLabel" data-action="remove" aria-label="${window.siyuan.languages.remove}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>
</div>
@@ -390,6 +390,14 @@ export const openEmojiPanel = (
<img data-type="text" class="emoji__dynamic-item${dynamicCurrentObj.type === "8" ? " emoji__dynamic-item--current" : ""}" src="${dynamicURL}type=8&color=${encodeURIComponent(dynamicCurrentObj.color)}&content=${encodeURIComponent(dynamicCurrentObj.content)}&id=${id}">
</div>
</div>
+ <div class="fn__none emojis__link" data-type="tab-link">
+ <input class="b3-text-field fn__block" data-type="network-icon-url" placeholder="${window.siyuan.languages.insertImgURL}">
+ <div class="emojis__link-preview"></div>
+ <div class="fn__flex">
+ <div class="fn__flex-1"></div>
+ <button class="b3-button b3-button--text" data-action="set-network-icon">${window.siyuan.languages.confirm}</button>
+ </div>
+ </div>
</div>
</div>`
});
@@ -404,11 +412,60 @@ export const openEmojiPanel = (
const dialogElement = dialog.element.querySelector(".b3-dialog") as HTMLElement;
dialogElement.style.justifyContent = "inherit";
dialogElement.style.alignItems = "inherit";
- const currentTab = window.siyuan.storage[Constants.LOCAL_EMOJIS].currentTab;
+ let currentTab = window.siyuan.storage[Constants.LOCAL_EMOJIS].currentTab;
+ const currentTabElement = dialog.element.querySelector(`[data-type="tab-${currentTab}"]`);
+ if (!currentTabElement || currentTabElement.classList.contains("fn__none")) {
+ currentTab = "emoji";
+ }
dialog.element.querySelector(`.emojis__tabheader [data-type="tab-${currentTab}"]`).classList.add("block__icon--active");
dialog.element.querySelector(`.emojis__tabbody [data-type="tab-${currentTab}"]`).classList.remove("fn__none");
setPosition(dialog.element.querySelector(".b3-dialog__container"), position.x, position.y, position.h, position.w);
dialog.element.querySelector(".emojis__item").classList.add("emojis__item--current");
+ const networkIconInputElement = dialog.element.querySelector('[data-type="network-icon-url"]') as HTMLInputElement;
+ const networkIconPreviewElement = dialog.element.querySelector(".emojis__link-preview");
+ networkIconInputElement.value = normalizeNetworkIconURL(dynamicImgElement?.getAttribute("src") || "") || "";
+ const renderNetworkIconPreview = () => {
+ const networkURL = normalizeNetworkIconURL(networkIconInputElement.value);
+ const imageHTML = networkURL ? genEmojiImageHTML(networkURL) : "";
+ networkIconPreviewElement.innerHTML = imageHTML ? Lute.Sanitize(imageHTML) : "";
+ };
+ const setNetworkIcon = () => {
+ const unicode = normalizeNetworkIconURL(networkIconInputElement.value);
+ if (!unicode) {
+ showMessage(window.siyuan.languages.invalid);
+ return;
+ }
+ if (type === "notebook") {
+ fetchPost("/api/notebook/setNotebookIcon", {
+ notebook: id,
+ icon: unicode
+ }, () => {
+ updateFileTreeEmoji(unicode, id, "iconNewNoteBook");
+ });
+ } else if (type === "doc") {
+ fetchPost("/api/attr/setBlockAttrs", {
+ id,
+ attrs: {"icon": unicode}
+ }, () => {
+ updateFileTreeEmoji(unicode, id);
+ updateOutlineEmoji(unicode, id);
+ });
+ }
+ if (callback) {
+ callback(unicode);
+ }
+ dialog.destroy();
+ };
+ networkIconInputElement.addEventListener("input", renderNetworkIconPreview);
+ networkIconInputElement.addEventListener("keydown", (event: KeyboardEvent) => {
+ if (event.isComposing || event.key !== "Enter") {
+ return;
+ }
+ setNetworkIcon();
+ event.preventDefault();
+ event.stopPropagation();
+ });
+ renderNetworkIconPreview();
const emojiSearchInputElement = dialog.element.querySelector('[data-type="tab-emoji"] .b3-text-field') as HTMLInputElement;
const emojisContentElement = dialog.element.querySelector(".emojis__panel");
emojiSearchInputElement.addEventListener("compositionend", () => {
@@ -555,6 +612,8 @@ export const openEmojiPanel = (
});
if (!isMobile() && currentTab === "emoji") {
emojiSearchInputElement.focus();
+ } else if (!isMobile() && currentTab === "link") {
+ networkIconInputElement.focus();
}
lazyLoadEmoji(dialog.element);
lazyLoadEmojiImg(dialog.element);
@@ -576,6 +635,11 @@ export const openEmojiPanel = (
});
}
break;
+ } else if (target.getAttribute("data-action") === "set-network-icon") {
+ setNetworkIcon();
+ event.preventDefault();
+ event.stopPropagation();
+ break;
} else if (target.getAttribute("data-action") === "remove") {
if (type === "notebook") {
fetchPost("/api/notebook/setNotebookIcon", {
@@ -648,6 +712,9 @@ export const openEmojiPanel = (
});
window.siyuan.storage[Constants.LOCAL_EMOJIS].currentTab = target.dataset.type.replace("tab-", "");
setStorageVal(Constants.LOCAL_EMOJIS, window.siyuan.storage[Constants.LOCAL_EMOJIS]);
+ if (target.dataset.type === "tab-link" && !isMobile()) {
+ networkIconInputElement.focus();
+ }
break;
} else if (target.classList.contains("color__square")) {
dynamicTextElements[0].value = target.getAttribute("style").replace("background-color:", "");
diff --git a/docs/SY-FORMAT.md b/docs/SY-FORMAT.md
index 40e1e273ed..50ee60024a 100644
--- a/docs/SY-FORMAT.md
+++ b/docs/SY-FORMAT.md
@@ -459,7 +459,7 @@ A `NodeTextMark` carrying color/effects (with `Properties.style`) **must be imme
A flat `map[string]string`.
-**Document-level (required):** `id`, `title`, `type` (always `"doc"`), `updated`. Optional: `icon` (emoji codepoint hex, e.g. `"1f4f0"`), `title-img` (CSS).
+**Document-level (required):** `id`, `title`, `type` (always `"doc"`), `updated`. Optional: `icon` (emoji codepoint hex, e.g. `"1f4f0"`; custom-icon filename; or HTTP(S) image URL), `title-img` (document title image style as a CSS declaration string, e.g. `background-image:url("assets/example.jpg")`).
**Block-level (required):** `id` (= the node's `ID`), `updated`. Optional: `style` (inline CSS), `fold: "1"` (collapsed), `colgroup` (table column widths), arbitrary `custom-*` custom attributes.
diff --git a/docs/SY-FORMAT.zh-CN.md b/docs/SY-FORMAT.zh-CN.md
index 756439e13c..4582eb4688 100644
--- a/docs/SY-FORMAT.zh-CN.md
+++ b/docs/SY-FORMAT.zh-CN.md
@@ -459,7 +459,7 @@ NodeList NodeList
扁平 `map[string]string`。
-**文档级必有**:`id`、`title`、`type`(恒 `"doc"`)、`updated`。可选:`icon`(emoji 码点十六进制,如 `"1f4f0"`)、`title-img`(CSS)。
+**文档级必有**:`id`、`title`、`type`(恒 `"doc"`)、`updated`。可选:`icon`(emoji 码点十六进制,如 `"1f4f0"`;自定义图标文件名;或 HTTP(S) 图片 URL)、`title-img`(题头图样式,CSS 声明字符串,如 `background-image:url("assets/example.jpg")`)。
**Block 级必有**:`id`(= 节点 `ID`)、`updated`。可选:`style`(行内 CSS)、`fold: "1"`(折叠态)、`colgroup`(表格列宽)、任意 `custom-*` 自定义属性。
diff --git a/docs/WORKSPACE.md b/docs/WORKSPACE.md
index 8c5e493d56..d8751ae7ac 100644
--- a/docs/WORKSPACE.md
+++ b/docs/WORKSPACE.md
@@ -170,7 +170,7 @@ The `BoxConf` struct:
|---|---|---|
| `name` | string | Notebook display name |
| `sort` | int | Sort weight |
-| `icon` | string | Icon (emoji hex code, e.g. `"1f3af"`; or a custom-icon filename) |
+| `icon` | string | Icon (emoji hex code, e.g. `"1f3af"`; a custom-icon filename; or an HTTP(S) image URL) |
| `closed` | bool | Whether the notebook is closed |
| `refCreateSaveBox` | string | Target notebook for docs created via block-ref |
| `refCreateSavePath` | string | Target path for docs created via block-ref |
diff --git a/docs/WORKSPACE.zh-CN.md b/docs/WORKSPACE.zh-CN.md
index 5a34f644c9..a00ea072db 100644
--- a/docs/WORKSPACE.zh-CN.md
+++ b/docs/WORKSPACE.zh-CN.md
@@ -170,7 +170,7 @@ data/<boxID>/
|---|---|---|
| `name` | string | 笔记本显示名称 |
| `sort` | int | 排序权重 |
-| `icon` | string | 图标(emoji hex 码,如 `"1f3af"`;或自定义图标文件名) |
+| `icon` | string | 图标(emoji hex 码,如 `"1f3af"`;自定义图标文件名;或 HTTP(S) 图片 URL) |
| `closed` | bool | 是否处于关闭状态 |
| `refCreateSaveBox` | string | 块引用时新建文档的目标笔记本 |
| `refCreateSavePath` | string | 块引用时新建文档的目标路径 |
diff --git a/kernel/cli/cmd/attr.go b/kernel/cli/cmd/attr.go
index 6cdf1fc83b..265dc25f5f 100644
--- a/kernel/cli/cmd/attr.go
+++ b/kernel/cli/cmd/attr.go
@@ -62,8 +62,8 @@ var attrSetCmd = &cobra.Command{
Long: `Set custom attributes on a block.
Common attributes:
- icon Emoji hex codepoint (e.g. "1f4ca"), emoji character (e.g. "📊"), custom image path (e.g. "1/b3log.png"), or dynamic icon URL (e.g.
- "api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx").
+ icon Emoji hex codepoint (e.g. "1f4ca"), emoji character (e.g. "📊"), custom image path (e.g. "1/b3log.png"), network image URL (e.g.
+ "https://example.com/icon.png"), or dynamic icon URL (e.g. "api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx").
title-img CSS background-image format (e.g. 'background-image:url("assets/example.jpg")').
DO NOT use a bare asset path.
tags Comma-separated tag names.
diff --git a/kernel/cli/cmd/notebook.go b/kernel/cli/cmd/notebook.go
index 3e3a59a735..88b8c9cb3b 100644
--- a/kernel/cli/cmd/notebook.go
+++ b/kernel/cli/cmd/notebook.go
@@ -198,7 +198,7 @@ func printNotebookTable(boxes []*model.Box) {
}
// notebookSetIconCmd 设置笔记本图标。
-// icon 取值格式:emoji hex 码点(如 "1f4ca")、emoji 字符、自定义图片路径或动态图标 URL。
+// icon 取值格式:emoji hex 码点(如 "1f4ca")、emoji 字符、自定义图片路径、网络图片 URL 或动态图标 URL。
var notebookSetIconCmd = &cobra.Command{
Use: "set-icon --id <id> --icon <icon>",
Short: "Set a notebook icon",
@@ -381,7 +381,7 @@ func init() {
notebookOpenCmd.Flags().String("id", "", "notebook ID")
notebookCloseCmd.Flags().String("id", "", "notebook ID")
notebookSetIconCmd.Flags().String("id", "", "notebook ID")
- notebookSetIconCmd.Flags().String("icon", "", "notebook icon: emoji hex codepoint like \"1f4ca\", emoji character like \"📊\", custom image path like \"1/b3log.png\", or dynamic icon URL like \"api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx\"")
+ notebookSetIconCmd.Flags().String("icon", "", "notebook icon: emoji hex codepoint like \"1f4ca\", emoji character like \"📊\", custom image path like \"1/b3log.png\", network image URL like \"https://example.com/icon.png\", or dynamic icon URL like \"api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx\"")
notebookRandomIconCmd.Flags().String("id", "", "notebook ID (optional; omit to update all notebooks)")
rootCmd.AddCommand(notebookCmd)
diff --git a/kernel/mcp/tools/attr.go b/kernel/mcp/tools/attr.go
index 12f32fdd1f..e40ca2b5db 100644
--- a/kernel/mcp/tools/attr.go
+++ b/kernel/mcp/tools/attr.go
@@ -34,7 +34,7 @@ var AttrTool = &Tool{
"action": {Type: "string", Description: "Operation", Enum: []string{"get", "set", "batch-get"}},
"id": {Type: "string", Description: "Block ID"},
"ids": {Type: "string", Description: "Comma-separated block IDs (for batch-get)"},
- "attrs": {Type: "object", Description: "Attribute key-value pairs (for set).\nCommon attributes:\n- icon: emoji hex codepoint like \"1f4ca\", emoji character like \"📊\", custom image path like \"1/b3log.png\", or dynamic icon URL like \"api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx\"\n- title-img: CSS format like 'background-image:url(\"assets/example.jpg\")', NOT a bare asset path\n- tags: comma-separated tag names"},
+ "attrs": {Type: "object", Description: "Attribute key-value pairs (for set).\nCommon attributes:\n- icon: emoji hex codepoint like \"1f4ca\", emoji character like \"📊\", custom image path like \"1/b3log.png\", network image URL like \"https://example.com/icon.png\", or dynamic icon URL like \"api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx\"\n- title-img: CSS format like 'background-image:url(\"assets/example.jpg\")', NOT a bare asset path\n- tags: comma-separated tag names"},
},
Required: []string{"action"},
},
diff --git a/kernel/mcp/tools/notebook.go b/kernel/mcp/tools/notebook.go
index a4bb4c0645..1d79aab299 100644
--- a/kernel/mcp/tools/notebook.go
+++ b/kernel/mcp/tools/notebook.go
@@ -35,7 +35,7 @@ var NotebookTool = &Tool{
"action": {Type: "string", Description: "Operation", Enum: []string{"list", "open", "close", "create", "rename", "remove", "set_icon", "random_icon"}},
"id": {Type: "string", Description: "Notebook ID (for open, close, rename, remove, set_icon, random_icon)"},
"name": {Type: "string", Description: "Notebook name (for create, rename)"},
- "icon": {Type: "string", Description: "Notebook icon (for set_icon). Emoji hex codepoint like \"1f4ca\", emoji character like \"📊\", custom image path like \"1/b3log.png\", or dynamic icon URL like \"api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx\""},
+ "icon": {Type: "string", Description: "Notebook icon (for set_icon). Emoji hex codepoint like \"1f4ca\", emoji character like \"📊\", custom image path like \"1/b3log.png\", network image URL like \"https://example.com/icon.png\", or dynamic icon URL like \"api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx\""},
},
Required: []string{"action"},
},
diff --git a/kernel/model/box.go b/kernel/model/box.go
index deb48a2691..c534230733 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -20,6 +20,7 @@ import (
"bytes"
"errors"
"fmt"
+ "net/url"
"os"
"path"
"path/filepath"
@@ -158,16 +159,10 @@ func ListNotebooks() (ret []*Box, err error) {
}
}
- icon := boxConf.Icon
- if strings.Contains(icon, ".") { // 说明是自定义图标
- // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
- icon = util.FilterUploadEmojiFileName(icon)
- }
-
box := &Box{
ID: id,
Name: boxConf.Name,
- Icon: icon,
+ Icon: filterBoxIcon(boxConf.Icon),
Sort: boxConf.Sort,
SortMode: boxConf.SortMode,
Closed: boxConf.Closed,
@@ -232,12 +227,7 @@ func (box *Box) GetConf() (ret *conf.BoxConf) {
return
}
- icon := ret.Icon
- if strings.Contains(icon, ".") {
- // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
- icon = util.FilterUploadEmojiFileName(icon)
- ret.Icon = icon
- }
+ ret.Icon = filterBoxIcon(ret.Icon)
return
}
@@ -955,6 +945,10 @@ func SetBoxIcon(boxID, icon string) {
}
func filterBoxIcon(icon string) string {
+ networkURL := strings.TrimSpace(icon)
+ if isNetworkIconURL(networkURL) {
+ return networkURL
+ }
if strings.Contains(icon, ".") {
// XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
icon = util.FilterUploadEmojiFileName(icon)
@@ -962,6 +956,11 @@ func filterBoxIcon(icon string) string {
return icon
}
+func isNetworkIconURL(icon string) bool {
+ u, err := url.Parse(icon)
+ return nil == err && "" != u.Host && ("http" == strings.ToLower(u.Scheme) || "https" == strings.ToLower(u.Scheme))
+}
+
func (box *Box) UpdateHistoryGenerated() {
boxLatestHistoryTime[box.ID] = time.Now()
}
diff --git a/kernel/model/box_icon_test.go b/kernel/model/box_icon_test.go
new file mode 100644
index 0000000000..1cfc3cf611
--- /dev/null
+++ b/kernel/model/box_icon_test.go
@@ -0,0 +1,67 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import "testing"
+
+func TestFilterBoxIconPreservesNetworkURL(t *testing.T) {
+ for _, icon := range []string{
+ "https://example.com/icon",
+ "http://127.0.0.1:8080/icon.png?size=80",
+ "HTTPS://example.com/icon.svg#preview",
+ } {
+ if got := filterBoxIcon(icon); got != icon {
+ t.Fatalf("network icon URL was changed [expected=%q, actual=%q]", icon, got)
+ }
+ }
+ if got := filterBoxIcon(" https://example.com/icon "); got != "https://example.com/icon" {
+ t.Fatalf("network icon URL was not trimmed [actual=%q]", got)
+ }
+}
+
+func TestIsNetworkIconURLRejectsOtherURLSchemes(t *testing.T) {
+ for _, icon := range []string{
+ "data:image/png;base64,AAAA",
+ "file:///tmp/icon.png",
+ "ftp://example.com/icon.png",
+ "//example.com/icon.png",
+ "https://",
+ } {
+ if isNetworkIconURL(icon) {
+ t.Fatalf("unsupported icon URL was accepted [%q]", icon)
+ }
+ }
+}
+
+func TestFilterBoxIconKeepsExistingIconFormats(t *testing.T) {
+ for _, icon := range []string{
+ "1f600",
+ "folder/icon.png",
+ "api/icon/getDynamicIcon?type=1",
+ } {
+ if got := filterBoxIcon(icon); got != icon {
+ t.Fatalf("existing icon value was changed [expected=%q, actual=%q]", icon, got)
+ }
+ }
+}
+
+func TestFilterBoxIconSanitizesCustomIconFilename(t *testing.T) {
+ icon := `" onerror="alert(1).png`
+ if got := filterBoxIcon(icon); got == icon {
+ t.Fatalf("unsafe custom icon filename was preserved [%q]", icon)
+ }
+}
diff --git a/kernel/model/import.go b/kernel/model/import.go
index df2aa29c23..49e885ced7 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -267,10 +267,7 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
if importedBoxConf != nil {
box := &Box{ID: boxID}
boxConf := box.GetConf()
- boxConf.Icon = importedBoxConf.Icon
- if strings.Contains(boxConf.Icon, ".") {
- boxConf.Icon = util.FilterUploadEmojiFileName(boxConf.Icon)
- }
+ boxConf.Icon = filterBoxIcon(importedBoxConf.Icon)
boxConf.RefCreateSavePath = importedBoxConf.RefCreateSavePath
boxConf.DocCreateSavePath = importedBoxConf.DocCreateSavePath
boxConf.DocCreateTemplatePath = importedBoxConf.DocCreateTemplatePath
@@ -323,7 +320,7 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
if icon := n.IALAttr("icon"); "" != icon {
// XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
- icon = util.FilterUploadEmojiFileName(icon)
+ icon = filterBoxIcon(icon)
n.SetIALAttr("icon", icon)
}