An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support localizing Base64 document and notebook icons https://github.com/siyuan-note/siyuan/issues/12926
Daniel722f44eebcb9
diff --git a/app/src/assets/scss/business/_emojis.scss b/app/src/assets/scss/business/_emojis.scssindex f587c56342..9037d3ae91 100644--- a/app/src/assets/scss/business/_emojis.scss+++ b/app/src/assets/scss/business/_emojis.scss@@ -110,6 +110,10 @@flex-shrink: 0;margin-top: 8px;}++ &-name {+ margin-top: 8px;+ }}&__content {diff --git a/app/src/emoji/iconValue.test.ts b/app/src/emoji/iconValue.test.tsindex 42ae608396..e332c852b5 100644--- a/app/src/emoji/iconValue.test.ts+++ b/app/src/emoji/iconValue.test.ts@@ -7,6 +7,7 @@ import {getIconValueKind,normalizeNetworkIconURL,normalizeRecentIconValue,+ parseBase64Image,updateRecentIconValues,} from "./iconValue";@@ -41,6 +42,31 @@ describe("getIconValueKind", () => {});});+describe("parseBase64Image", () => {+ it("decodes supported image data URLs", () => {+ const parsed = parseBase64Image(" data:image/png;base64,AQID ");+ assert.ok(parsed);+ assert.equal(parsed.mimeType, "image/png");+ assert.equal(parsed.extension, "png");+ assert.deepEqual([...parsed.bytes], [1, 2, 3]);++ const svg = parseBase64Image("data:image/svg+xml;charset=utf-8;base64,PHN2Zz48L3N2Zz4=");+ assert.ok(svg);+ assert.equal(svg.extension, "svg");+ });++ it("rejects unsupported, empty, and malformed data URLs", () => {+ [+ "",+ "data:text/plain;base64,AQID",+ "data:image/bmp;base64,AQID",+ "data:image/png,AQID",+ "data:image/png;base64,",+ "data:image/png;base64,***",+ ].forEach(item => assert.equal(parseBase64Image(item), undefined));+ });+});+describe("dynamic icon recent values", () => {it("removes source IDs and canonicalizes query parameters", () => {assert.equal(diff --git a/app/src/emoji/iconValue.ts b/app/src/emoji/iconValue.tsindex 48a5c40250..9ba5aede71 100644--- a/app/src/emoji/iconValue.ts+++ b/app/src/emoji/iconValue.ts@@ -2,8 +2,20 @@ import {escapeAttr, escapeHtml} from "../util/escape";const DYNAMIC_ICON_PREFIX = "api/icon/getDynamicIcon";const URL_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z\d+.-]*:/;+const BASE64_IMAGE_MIME_EXTENSIONS: Record<string, string> = {+ "image/gif": "gif",+ "image/jpeg": "jpg",+ "image/png": "png",+ "image/svg+xml": "svg",+ "image/webp": "webp",+};export type TIconValueKind = "unicode" | "custom" | "dynamic" | "network" | "invalid";+export interface IBase64Image {+ bytes: Uint8Array,+ extension: string,+ mimeType: string,+}export const normalizeNetworkIconURL = (value: string): string | undefined => {const icon = value.trim();@@ -19,6 +31,38 @@ export const normalizeNetworkIconURL = (value: string): string | undefined => {return url.href;};+export const parseBase64Image = (value: string): IBase64Image | undefined => {+ const icon = value.trim();+ const commaIndex = icon.indexOf(",");+ if (commaIndex < 0) {+ return;+ }++ const header = icon.substring(0, commaIndex);+ const headerMatch = header.match(/^data:(image\/(?:gif|jpeg|png|svg\+xml|webp))(?:;[^,;]+)*;base64$/i);+ if (!headerMatch) {+ return;+ }+ const mimeType = headerMatch[1].toLowerCase();+ try {+ const binary = atob(icon.substring(commaIndex + 1).replace(/\s/g, ""));+ if (!binary) {+ return;+ }+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) {+ bytes[i] = binary.charCodeAt(i);+ }+ return {+ bytes,+ extension: BASE64_IMAGE_MIME_EXTENSIONS[mimeType],+ mimeType,+ };+ } catch {+ return;+ }+};+export const getIconValueKind = (value: string): TIconValueKind => {if (value.startsWith(DYNAMIC_ICON_PREFIX)) {return "dynamic";diff --git a/app/src/emoji/index.ts b/app/src/emoji/index.tsindex f1ea124e71..95ddad1632 100644--- a/app/src/emoji/index.ts+++ b/app/src/emoji/index.ts@@ -1,5 +1,5 @@import {getRandom, isMobile} from "../util/functions";-import {fetchPost} from "../util/fetch";+import {fetchPost, fetchSyncPost} from "../util/fetch";import {Constants} from "../constants";/// #if !MOBILEimport {Files} from "../layout/dock/Files";@@ -19,6 +19,7 @@ import {getIconValueKind,normalizeNetworkIconURL,normalizeRecentIconValue,+ parseBase64Image,updateRecentIconValues,} from "./iconValue";import {showMessage} from "../dialog/message";@@ -425,7 +426,8 @@ export const openEmojiPanel = (</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}">+ <input class="b3-text-field fn__block" data-type="network-icon-url" placeholder="${window.siyuan.languages.insertImgURL} / Base64">+ <input class="b3-text-field fn__block fn__none emojis__link-name" data-type="custom-icon-name" placeholder="${window.siyuan.languages.fileName} (path/to/icon)"><div class="fn__flex emojis__link-action"><div class="fn__flex-1"></div><button class="b3-button b3-button--text" data-action="set-network-icon">${window.siyuan.languages.confirm}</button>@@ -456,19 +458,24 @@ export const openEmojiPanel = (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 customIconNameElement = dialog.element.querySelector('[data-type="custom-icon-name"]') as HTMLInputElement;const networkIconPreviewElement = dialog.element.querySelector(".emojis__link-preview");networkIconInputElement.value = normalizeNetworkIconURL(dynamicImgElement?.getAttribute("src") || "") || "";const renderNetworkIconPreview = () => {const networkURL = normalizeNetworkIconURL(networkIconInputElement.value);+ const base64Image = parseBase64Image(networkIconInputElement.value);+ customIconNameElement.classList.toggle("fn__none", !networkIconInputElement.value.trim().toLowerCase().startsWith("data:image/"));+ networkIconPreviewElement.innerHTML = "";+ if (base64Image) {+ const imageElement = document.createElement("img");+ imageElement.src = networkIconInputElement.value.trim();+ networkIconPreviewElement.append(imageElement);+ return;+ }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;- }+ const applyLinkIcon = (unicode: string) => {if (type === "notebook") {fetchPost("/api/notebook/setNotebookIcon", {notebook: id,@@ -491,14 +498,48 @@ export const openEmojiPanel = (addEmoji(unicode);dialog.destroy();};- networkIconInputElement.addEventListener("input", renderNetworkIconPreview);- networkIconInputElement.addEventListener("keydown", (event: KeyboardEvent) => {- if (event.isComposing || event.key !== "Enter") {+ const setNetworkIcon = async () => {+ const networkURL = normalizeNetworkIconURL(networkIconInputElement.value);+ if (networkURL) {+ applyLinkIcon(networkURL);+ return;+ }++ const base64Image = parseBase64Image(networkIconInputElement.value);+ if (!base64Image) {+ showMessage(window.siyuan.languages.invalid);return;}- setNetworkIcon();- event.preventDefault();- event.stopPropagation();+ if (!customIconNameElement.value.trim()) {+ showMessage(window.siyuan.languages.nameEmpty);+ customIconNameElement.focus();+ return;+ }++ const formData = new FormData();+ formData.append("name", customIconNameElement.value);+ formData.append("file", new File(+ [base64Image.bytes],+ `icon.${base64Image.extension}`,+ {type: base64Image.mimeType},+ ));+ const response = await fetchSyncPost("/api/system/addCustomEmoji", formData);+ if (response.code !== 0) {+ return;+ }+ reloadEmoji();+ applyLinkIcon(response.data.path);+ };+ networkIconInputElement.addEventListener("input", renderNetworkIconPreview);+ [networkIconInputElement, customIconNameElement].forEach(item => {+ item.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;diff --git a/kernel/api/router.go b/kernel/api/router.goindex 53ec08c23a..cdfd8b2de8 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -45,6 +45,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("GET", "/api/icon/getDynamicIcon", model.CheckAuth, getDynamicIcon)ginServer.Handle("POST", "/api/system/getEmojiConf", model.CheckAuth, getEmojiConf)+ ginServer.Handle("POST", "/api/system/addCustomEmoji", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, addCustomEmoji)ginServer.Handle("POST", "/api/system/setAPIToken", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAPIToken)ginServer.Handle("POST", "/api/system/setAccessAuthCode", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAccessAuthCode)ginServer.Handle("POST", "/api/system/setFollowSystemLockScreen", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setFollowSystemLockScreen)diff --git a/kernel/api/system.go b/kernel/api/system.goindex c84048f728..08cb992b3c 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -17,8 +17,10 @@package apiimport (+ "bytes""encoding/json""fmt"+ "image""io""net/http""os"@@ -192,63 +194,7 @@ func getEmojiConf(c *gin.Context) {custom["items"] = itemsif gulu.File.IsDir(customConfDir) {model.ClearCustomEmojis()- customEmojis, err := os.ReadDir(customConfDir)- if err != nil {- logging.LogErrorf("read custom emojis failed: %s", err)- } else {- for _, customEmoji := range customEmojis {- name := customEmoji.Name()- if strings.HasPrefix(name, ".") {- continue- }-- if !util.IsValidUploadFileName(html.UnescapeString(name)) {- emojiFullName := filepath.Join(customConfDir, name)- name = util.FilterUploadEmojiFileName(name)- fullPathFilteredName := filepath.Join(customConfDir, name)- // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034- logging.LogWarnf("renaming invalid custom emoji file [%s] to [%s]", name, fullPathFilteredName)- if removeErr := filelock.Rename(emojiFullName, fullPathFilteredName); nil != removeErr {- logging.LogErrorf("renaming invalid custom emoji file to [%s] failed: %s", fullPathFilteredName, removeErr)- }- }-- if customEmoji.IsDir() {- // 子级- subCustomEmojis, err := os.ReadDir(filepath.Join(customConfDir, name))- if err != nil {- logging.LogErrorf("read custom emojis failed: %s", err)- continue- }-- for _, subCustomEmoji := range subCustomEmojis {- if subCustomEmoji.IsDir() {- continue- }-- subName := subCustomEmoji.Name()- if strings.HasPrefix(subName, ".") {- continue- }-- if !util.IsValidUploadFileName(html.UnescapeString(subName)) {- emojiFullName := filepath.Join(customConfDir, name, subName)- fullPathFilteredName := filepath.Join(customConfDir, name, util.FilterUploadEmojiFileName(subName))- // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034- logging.LogWarnf("renaming invalid custom emoji file [%s] to [%s]", subName, fullPathFilteredName)- if removeErr := filelock.Rename(emojiFullName, fullPathFilteredName); nil != removeErr {- logging.LogErrorf("renaming invalid custom emoji file to [%s] failed: %s", fullPathFilteredName, removeErr)- }- }-- addCustomEmoji(name+"/"+subName, &items)- }- continue- }-- addCustomEmoji(name, &items)- }- }+ readCustomEmojis(customConfDir, "", &items)}custom["items"] = itemsconf = append([]map[string]any{custom}, conf...)@@ -257,7 +203,42 @@ func getEmojiConf(c *gin.Context) {return}-func addCustomEmoji(name string, items *[]map[string]any) {+func readCustomEmojis(rootDir, relativeDir string, items *[]map[string]any) {+ dir := filepath.Join(rootDir, filepath.FromSlash(relativeDir))+ customEmojis, err := os.ReadDir(dir)+ if err != nil {+ logging.LogErrorf("read custom emojis failed: %s", err)+ return+ }++ for _, customEmoji := range customEmojis {+ name := customEmoji.Name()+ if strings.HasPrefix(name, ".") {+ continue+ }++ if !util.IsValidUploadFileName(html.UnescapeString(name)) {+ oldPath := filepath.Join(dir, name)+ name = util.FilterUploadEmojiFileName(name)+ newPath := filepath.Join(dir, name)+ // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034+ logging.LogWarnf("renaming invalid custom emoji file [%s] to [%s]", oldPath, newPath)+ if renameErr := filelock.Rename(oldPath, newPath); nil != renameErr {+ logging.LogErrorf("renaming invalid custom emoji file to [%s] failed: %s", newPath, renameErr)+ continue+ }+ }++ relativePath := filepath.ToSlash(filepath.Join(relativeDir, name))+ if customEmoji.IsDir() {+ readCustomEmojis(rootDir, relativePath, items)+ continue+ }+ appendCustomEmoji(relativePath, items)+ }+}++func appendCustomEmoji(name string, items *[]map[string]any) {ext := filepath.Ext(name)nameWithoutExt := strings.TrimSuffix(name, ext)emoji := map[string]any{@@ -273,6 +254,131 @@ func addCustomEmoji(name string, items *[]map[string]any) {model.AddCustomEmoji(nameWithoutExt, imgSrc)}+const maxCustomEmojiSize = 10 * 1024 * 1024++func addCustomEmoji(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ fileHeader, err := c.FormFile("file")+ if err != nil {+ ret.Code = http.StatusBadRequest+ ret.Msg = "Field [file] must not be empty"+ return+ }+ file, err := fileHeader.Open()+ if err != nil {+ ret.Code = http.StatusBadRequest+ ret.Msg = err.Error()+ return+ }+ defer file.Close()++ data, err := io.ReadAll(io.LimitReader(file, maxCustomEmojiSize+1))+ if err != nil {+ ret.Code = http.StatusBadRequest+ ret.Msg = err.Error()+ return+ }+ if len(data) > maxCustomEmojiSize {+ ret.Code = http.StatusRequestEntityTooLarge+ ret.Msg = "custom emoji file is too large"+ return+ }++ data, ext, err := normalizeCustomEmojiData(data)+ if err != nil {+ ret.Code = http.StatusBadRequest+ ret.Msg = err.Error()+ return+ }+ relativePath, err := normalizeCustomEmojiPath(c.PostForm("name"), ext)+ if err != nil {+ ret.Code = http.StatusBadRequest+ ret.Msg = err.Error()+ return+ }++ emojisDir := filepath.Join(util.DataDir, "emojis")+ emojiPath := util.GetUniqueFilename(filepath.Join(emojisDir, filepath.FromSlash(relativePath)))+ if err = os.MkdirAll(filepath.Dir(emojiPath), 0755); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ if err = filelock.WriteFile(emojiPath, data); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }++ model.IncSync()+ relativePath, _ = filepath.Rel(emojisDir, emojiPath)+ relativePath = filepath.ToSlash(relativePath)+ ret.Data = map[string]any{"path": relativePath}+}++func normalizeCustomEmojiData(data []byte) (normalized []byte, ext string, err error) {+ if len(data) == 0 {+ return nil, "", fmt.Errorf("custom emoji file must not be empty")+ }++ raster := true+ switch http.DetectContentType(data) {+ case "image/png":+ ext = ".png"+ case "image/jpeg":+ ext = ".jpg"+ case "image/gif":+ ext = ".gif"+ case "image/webp":+ ext = ".webp"+ default:+ raster = false+ }+ if raster {+ config, _, decodeErr := image.DecodeConfig(bytes.NewReader(data))+ if decodeErr != nil || config.Width < 1 || config.Height < 1 || config.Width > 16384 || config.Height > 16384 ||+ int64(config.Width)*int64(config.Height) > 100*1000*1000 {+ return nil, "", fmt.Errorf("invalid custom emoji image")+ }+ return data, ext, nil+ }++ sanitizedSVG, sanitizeErr := util.SanitizeSVG(string(data))+ if sanitizeErr == nil {+ return []byte(sanitizedSVG), ".svg", nil+ }+ return nil, "", fmt.Errorf("unsupported custom emoji image format")+}++func normalizeCustomEmojiPath(name, ext string) (string, error) {+ name = strings.TrimSpace(strings.ReplaceAll(name, "\\", "/"))+ parts := strings.Split(name, "/")+ if len(parts) == 0 {+ return "", fmt.Errorf("custom emoji name must not be empty")+ }++ lastIndex := len(parts) - 1+ switch strings.ToLower(filepath.Ext(parts[lastIndex])) {+ case ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg":+ parts[lastIndex] = strings.TrimSuffix(parts[lastIndex], filepath.Ext(parts[lastIndex]))+ }+ for i, part := range parts {+ part = strings.TrimSpace(part)+ if part == "" || part == "." || part == ".." {+ return "", fmt.Errorf("invalid custom emoji name")+ }+ part = util.FilterUploadFileName(part)+ if part == "" || part == "." || part == ".." {+ return "", fmt.Errorf("invalid custom emoji name")+ }+ parts[i] = part+ }+ parts[lastIndex] += ext+ return strings.Join(parts, "/"), nil+}+func checkUpdate(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/system_emoji_test.go b/kernel/api/system_emoji_test.gonew file mode 100644index 0000000000..a379ac035d--- /dev/null+++ b/kernel/api/system_emoji_test.go@@ -0,0 +1,111 @@+// 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 api++import (+ "bytes"+ "image"+ "image/png"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestNormalizeCustomEmojiPath(t *testing.T) {+ tests := []struct {+ name string+ input string+ ext string+ expected string+ valid bool+ }{+ {name: "plain", input: "icon", ext: ".png", expected: "icon.png", valid: true},+ {name: "nested", input: "folder/sub/icon.jpg", ext: ".webp", expected: "folder/sub/icon.webp", valid: true},+ {name: "backslash", input: `folder\icon`, ext: ".gif", expected: "folder/icon.gif", valid: true},+ {name: "parent", input: "folder/../icon", ext: ".png"},+ {name: "empty segment", input: "folder//icon", ext: ".png"},+ {name: "empty", input: "", ext: ".png"},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ actual, err := normalizeCustomEmojiPath(test.input, test.ext)+ if test.valid {+ if err != nil {+ t.Fatalf("normalize custom emoji path failed: %s", err)+ }+ if actual != test.expected {+ t.Fatalf("expected [%s], got [%s]", test.expected, actual)+ }+ } else if err == nil {+ t.Fatalf("expected invalid path, got [%s]", actual)+ }+ })+ }+}++func TestNormalizeCustomEmojiData(t *testing.T) {+ var pngData bytes.Buffer+ if err := png.Encode(&pngData, image.NewRGBA(image.Rect(0, 0, 1, 1))); err != nil {+ t.Fatalf("encode png failed: %s", err)+ }++ data, ext, err := normalizeCustomEmojiData(pngData.Bytes())+ if err != nil {+ t.Fatalf("normalize png failed: %s", err)+ }+ if ext != ".png" || !bytes.Equal(data, pngData.Bytes()) {+ t.Fatalf("unexpected normalized png")+ }++ svg := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><circle cx="1" cy="1" r="1"/></svg>`)+ data, ext, err = normalizeCustomEmojiData(svg)+ if err != nil {+ t.Fatalf("normalize svg failed: %s", err)+ }+ if ext != ".svg" || bytes.Contains(data, []byte("<script")) {+ t.Fatalf("unsafe svg was not sanitized")+ }++ if _, _, err = normalizeCustomEmojiData([]byte("not an image")); err == nil {+ t.Fatalf("expected invalid image data")+ }+}++func TestReadCustomEmojisRecursively(t *testing.T) {+ model.ClearCustomEmojis()+ t.Cleanup(model.ClearCustomEmojis)+ root := t.TempDir()+ nestedDir := filepath.Join(root, "folder", "sub")+ if err := os.MkdirAll(nestedDir, 0755); err != nil {+ t.Fatalf("create nested custom emoji directory failed: %s", err)+ }+ if err := os.WriteFile(filepath.Join(nestedDir, "icon.png"), []byte("test"), 0644); err != nil {+ t.Fatalf("write custom emoji failed: %s", err)+ }++ items := []map[string]any{}+ readCustomEmojis(root, "", &items)+ if len(items) != 1 {+ t.Fatalf("expected one custom emoji, got %d", len(items))+ }+ if actual := items[0]["unicode"]; actual != "folder/sub/icon.png" {+ t.Fatalf("unexpected custom emoji path [%v]", actual)+ }+}