An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Prevent virtual references from matching HTML entities https://github.com/siyuan-note/siyuan/issues/16872
Danielc39286de2306
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex 8f78c2298d..dba366d876 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -1036,8 +1036,8 @@ func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBaccontinue}- newText := markReplaceSpanWithSplit(text, mentionKeywords, search.GetMarkSpanStart(search.MarkDataType), search.GetMarkSpanEnd())- if text != newText {+ newText, matched := markReplaceSpanWithSplit(text, mentionKeywords, search.GetMarkSpanStart(search.MarkDataType), search.GetMarkSpanEnd())+ if matched {tmp = append(tmp, b)k := gulu.Str.SubstringsBetween(newText, search.GetMarkSpanStart(search.MarkDataType), search.GetMarkSpanEnd())diff --git a/kernel/model/search.go b/kernel/model/search.goindex 10d60e5418..88348c7d10 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -2519,11 +2519,16 @@ func markReplaceSpan(n *ast.Node, unlinks *[]*ast.Node, keywords []string, markS}// markReplaceSpanWithSplit 用于处理虚拟引用和反链提及高亮。-func markReplaceSpanWithSplit(text string, keywords []string, replacementStart, replacementEnd string) (ret string) {+func markReplaceSpanWithSplit(text string, keywords []string, replacementStart, replacementEnd string) (ret string, matched bool) {// 虚拟引用和反链提及关键字按最长匹配优先 https://github.com/siyuan-note/siyuan/issues/7465sort.Slice(keywords, func(i, j int) bool { return len(keywords[i]) > len(keywords[j]) })- tmp := search.EncloseHighlighting(text, keywords, replacementStart, replacementEnd, Conf.Search.CaseSensitive, true)+ tmp, matched := search.EncloseHighlightingRaw(text, keywords, replacementStart, replacementEnd, Conf.Search.CaseSensitive, true)+ if !matched {+ ret = tmp+ return+ }+parts := strings.Split(tmp, replacementEnd)buf := bytes.Buffer{}for i := range len(parts) {@@ -2543,6 +2548,7 @@ func markReplaceSpanWithSplit(text string, keywords []string, replacementStart,buf.WriteString(replacementEnd)}ret = buf.String()+ matched = strings.Contains(ret, replacementStart)return}diff --git a/kernel/model/virtualref_test.go b/kernel/model/virtualref_test.gonew file mode 100644index 0000000000..0df9b59494--- /dev/null+++ b/kernel/model/virtualref_test.go@@ -0,0 +1,89 @@+// 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"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestProcessVirtualRefDoesNotMatchHTMLEntity(t *testing.T) {+ previousConf := Conf+ Conf = NewAppConf()+ Conf.Editor = conf.NewEditor()+ Conf.Search = conf.NewSearch()+ Conf.Editor.VirtualBlockRef = true+ t.Cleanup(func() {+ Conf = previousConf+ })++ const blockDOM = `<div data-node-id="20260725010000-abcdefg" data-type="NodeParagraph" class="p"><div contenteditable="true" spellcheck="false">amp A&B</div><div class="protyle-attr" contenteditable="false"></div></div>`+ luteEngine := util.NewLute()+ tree := luteEngine.BlockDOM2Tree(blockDOM)++ var textNode *ast.Node+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeText == n.Type && "amp A&B" == string(n.Tokens) {+ textNode = n+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if nil == textNode {+ t.Fatal("BlockDOM 中的 & 没有生成预期的文本节点")+ }++ var unlinks []*ast.Node+ if !processVirtualRef(textNode, &unlinks, []string{"amp"}, map[string]int{}, luteEngine) {+ t.Fatal("真实的 amp 没有生成虚拟引用")+ }+ for _, unlink := range unlinks {+ unlink.Unlink()+ }++ var virtualRefContents []string+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == n.Type && n.IsTextMarkType("virtual-block-ref") {+ virtualRefContents = append(virtualRefContents, n.TextMarkTextContent)+ }+ return ast.WalkContinue+ })+ if 1 != len(virtualRefContents) || "amp" != virtualRefContents[0] {+ t.Fatalf("virtual references = %q, want [amp]", virtualRefContents)+ }+}++func TestMarkReplaceSpanWithSplitReportsFinalMatch(t *testing.T) {+ previousConf := Conf+ Conf = NewAppConf()+ Conf.Search = conf.NewSearch()+ t.Cleanup(func() {+ Conf = previousConf+ })++ start := "<span data-type=\"virtual-block-ref\">"+ got, matched := markReplaceSpanWithSplit("中a", []string{"中"}, start, "</span>")+ if "中a" != got {+ t.Fatalf("result = %q, want %q", got, "中a")+ }+ if matched {+ t.Fatal("已被边界处理撤销的高亮仍返回命中状态")+ }+}diff --git a/kernel/model/virutalref.go b/kernel/model/virutalref.goindex ab19baeb69..a18599107b 100644--- a/kernel/model/virutalref.go+++ b/kernel/model/virutalref.go@@ -214,8 +214,8 @@ func processVirtualRef(n *ast.Node, unlinks *[]*ast.Node, virtualBlockRefKeywordreturn false}- newContent := markReplaceSpanWithSplit(content, virtualBlockRefKeywords, search.GetMarkSpanStart(search.VirtualBlockRefDataType), search.GetMarkSpanEnd())- if content != newContent {+ newContent, matched := markReplaceSpanWithSplit(content, virtualBlockRefKeywords, search.GetMarkSpanStart(search.VirtualBlockRefDataType), search.GetMarkSpanEnd())+ if matched {// 虚拟引用排除命中自身块命名和别名的情况 https://github.com/siyuan-note/siyuan/issues/3185var blockKeys []stringif name := parentBlock.IALAttr("name"); "" != name {diff --git a/kernel/search/mark.go b/kernel/search/mark.goindex 3ec00473d6..b059e87340 100644--- a/kernel/search/mark.go+++ b/kernel/search/mark.go@@ -23,6 +23,7 @@ import ("unicode/utf8""github.com/88250/gulu"+ "github.com/88250/lute/html""github.com/88250/lute/lex""github.com/siyuan-note/siyuan/kernel/util")@@ -81,6 +82,60 @@ func SplitKeyword(keyword string) (keywords []string) {}func EncloseHighlighting(text string, keywords []string, openMark, closeMark string, caseSensitive, splitWords bool) (ret string) {+ reg, err := compileHighlightingRegexp(keywords, caseSensitive, splitWords, true)+ ret = util.EscapeHTML(text)++ ret = strings.ReplaceAll(ret, """, "\ue000")+ ret = strings.ReplaceAll(ret, "<", "\ue001")+ ret = strings.ReplaceAll(ret, ">", "\ue002")+ ret = strings.ReplaceAll(ret, "'", "\ue003")+ if err == nil {+ ret = reg.ReplaceAllStringFunc(ret, func(s string) string { return openMark + s + closeMark })+ }+ ret = strings.ReplaceAll(ret, "\ue000", """)+ ret = strings.ReplaceAll(ret, "\ue001", "<")+ ret = strings.ReplaceAll(ret, "\ue002", ">")+ ret = strings.ReplaceAll(ret, "\ue003", "'")++ // 搜索结果预览包含转义符问题 Search results preview contains escape character issue https://github.com/siyuan-note/siyuan/issues/9790+ ret = strings.ReplaceAll(ret, "\\<span", "\\\\<span")+ return+}++// EncloseHighlightingRaw 在原始文本中匹配关键字,并在插入高亮标记时转义文本。+func EncloseHighlightingRaw(text string, keywords []string, openMark, closeMark string, caseSensitive, splitWords bool) (ret string, matched bool) {+ reg, err := compileHighlightingRegexp(keywords, caseSensitive, splitWords, false)+ if err != nil {+ ret = html.EscapeString(text)+ return+ }++ indexes := reg.FindAllStringIndex(text, -1)+ if 1 > len(indexes) {+ ret = html.EscapeString(text)+ return+ }++ var buf strings.Builder+ buf.Grow(len(text) + len(indexes)*(len(openMark)+len(closeMark)))+ last := 0+ for _, index := range indexes {+ buf.WriteString(html.EscapeString(text[last:index[0]]))+ buf.WriteString(openMark)+ buf.WriteString(html.EscapeString(text[index[0]:index[1]]))+ buf.WriteString(closeMark)+ last = index[1]+ }+ buf.WriteString(html.EscapeString(text[last:]))+ ret = buf.String()++ // 避免反斜杠转义生成的高亮标签 https://github.com/siyuan-note/siyuan/issues/9790+ ret = strings.ReplaceAll(ret, "\\<span", "\\\\<span")+ matched = true+ return+}++func compileHighlightingRegexp(keywords []string, caseSensitive, splitWords, escapeHTML bool) (ret *regexp.Regexp, err error) {ic := "(?i)"if caseSensitive {ic = "(?)"@@ -97,11 +152,14 @@ func EncloseHighlighting(text string, keywords []string, openMark, closeMark strif splitWords {wordBoundary = lex.IsASCIILetterNums(gulu.Str.ToBytes(k)) // Improve virtual reference split words https://github.com/siyuan-note/siyuan/issues/7833}+ if escapeHTML {+ k = util.EscapeHTML(k)+ }if !util.SearchHanSensitive {// 不区分繁简:将关键字逐字符展开为繁简等价字符类,如 "诗经" -> "[诗詩][经經]"- k = hanInsensitiveRegexp(util.EscapeHTML(k))+ k = hanInsensitiveRegexp(k)} else {- k = regexp.QuoteMeta(util.EscapeHTML(k))+ k = regexp.QuoteMeta(k)}re.WriteString("(")if wordBoundary {@@ -117,23 +175,7 @@ func EncloseHighlighting(text string, keywords []string, openMark, closeMark str}}re.WriteString(")")-- ret = util.EscapeHTML(text)-- ret = strings.ReplaceAll(ret, """, "\ue000")- ret = strings.ReplaceAll(ret, "<", "\ue001")- ret = strings.ReplaceAll(ret, ">", "\ue002")- ret = strings.ReplaceAll(ret, "'", "\ue003")- if reg, err := regexp.Compile(re.String()); err == nil {- ret = reg.ReplaceAllStringFunc(ret, func(s string) string { return openMark + s + closeMark })- }- ret = strings.ReplaceAll(ret, "\ue000", """)- ret = strings.ReplaceAll(ret, "\ue001", "<")- ret = strings.ReplaceAll(ret, "\ue002", ">")- ret = strings.ReplaceAll(ret, "\ue003", "'")-- // 搜索结果预览包含转义符问题 Search results preview contains escape character issue https://github.com/siyuan-note/siyuan/issues/9790- ret = strings.ReplaceAll(ret, "\\<span", "\\\\<span")+ ret, err = regexp.Compile(re.String())return}diff --git a/kernel/search/mark_test.go b/kernel/search/mark_test.gonew file mode 100644index 0000000000..fd2c05e9b4--- /dev/null+++ b/kernel/search/mark_test.go@@ -0,0 +1,133 @@+// 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 search++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestEncloseHighlightingRaw(t *testing.T) {+ old := util.SearchHanSensitive+ util.SearchHanSensitive = true+ t.Cleanup(func() {+ util.SearchHanSensitive = old+ })++ start := GetMarkSpanStart(VirtualBlockRefDataType)+ end := GetMarkSpanEnd()+ tests := []struct {+ name string+ text string+ keywords []string+ want string+ matched bool+ }{+ {+ name: "entity text is not matched",+ text: "amp A&B",+ keywords: []string{"amp"},+ want: start + "amp" + end + " A&B",+ matched: true,+ },+ {+ name: "entity-only match is ignored",+ text: "A&B",+ keywords: []string{"amp"},+ want: "A&B",+ matched: false,+ },+ {+ name: "numeric entity text is not matched",+ text: "de Casteljau's 39",+ keywords: []string{"39"},+ want: "de Casteljau's " + start + "39" + end,+ matched: true,+ },+ {+ name: "double quote entity text is not matched",+ text: "\"quoted\" 34",+ keywords: []string{"34"},+ want: ""quoted" " + start + "34" + end,+ matched: true,+ },+ {+ name: "tag entity names are not matched",+ text: "lt < gt >",+ keywords: []string{"lt", "gt"},+ want: start + "lt" + end + " < " + start + "gt" + end + " >",+ matched: true,+ },+ {+ name: "carriage return is escaped between matches",+ text: "amp\r13",+ keywords: []string{"amp", "13"},+ want: start + "amp" + end + " " + start + "13" + end,+ matched: true,+ },+ {+ name: "keyword containing ampersand",+ text: "R&D",+ keywords: []string{"R&D"},+ want: start + "R&D" + end,+ matched: true,+ },+ {+ name: "keyword containing HTML tag characters",+ text: "<foo>",+ keywords: []string{"<foo>"},+ want: start + "<foo>" + end,+ matched: true,+ },+ {+ name: "unmatched HTML is escaped",+ text: "<script>alert(1)</script>",+ keywords: []string{"missing"},+ want: "<script>alert(1)</script>",+ matched: false,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ got, matched := EncloseHighlightingRaw(test.text, test.keywords, start, end, true, true)+ if test.want != got {+ t.Fatalf("result = %q, want %q", got, test.want)+ }+ if test.matched != matched {+ t.Fatalf("matched = %v, want %v", matched, test.matched)+ }+ })+ }+}++func TestEncloseHighlightingRawHanInsensitive(t *testing.T) {+ old := util.SearchHanSensitive+ util.SearchHanSensitive = false+ t.Cleanup(func() {+ util.SearchHanSensitive = old+ })++ got, matched := EncloseHighlightingRaw("詩經研究", []string{"诗经"}, "<mark>", "</mark>", false, false)+ if want := "<mark>詩經</mark>研究"; want != got {+ t.Fatalf("result = %q, want %q", got, want)+ }+ if !matched {+ t.Fatal("繁简不敏感匹配未返回命中状态")+ }+}