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: Reject semantic search replacements https://github.com/siyuan-note/siyuan/issues/20226
Daniel876c27087120
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.tsindex 7447c02f63..1ba75f2a81 100644--- a/app/src/mobile/menu/search.ts+++ b/app/src/mobile/menu/search.ts@@ -45,7 +45,7 @@ const replace = (element: Element, config: Config.IUILayoutTabSearchConfig, isAlif (window.siyuan.isPublish) {return;}- if (config.method === 2) {+ if (config.method === 2 || config.method === 4) {showMessage(window.siyuan.languages._kernel[132]);return;}diff --git a/app/src/mobile/menu/searchReplace.test.ts b/app/src/mobile/menu/searchReplace.test.tsnew file mode 100644index 0000000000..f9d68e7fc8--- /dev/null+++ b/app/src/mobile/menu/searchReplace.test.ts@@ -0,0 +1,35 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";++for (const path of ["src/search/util.ts", "src/mobile/menu/search.ts"]) {+ const source = createSourceFile(path, readFileSync(path, "utf8"), ScriptTarget.ES2021, true);+ const declaration = source.statements.filter(isVariableStatement).flatMap(statement =>+ Array.from(statement.declarationList.declarations)).find(item => item.name.getText(source) === "replace");+ const compiled = transpileModule(`const ${declaration.getText(source)}; globalThis.replace = replace;`, {+ compilerOptions: {target: ScriptTarget.ES2021},+ }).outputText;++ for (const method of [2, 4]) {+ for (const isAll of [false, true]) {+ test(`${path}: method ${method} rejects ${isAll ? "all" : "single"} replacement before accessing results`, () => {+ const messages: string[] = [];+ const context: any = {+ window: {siyuan: {isPublish: false, languages: {_kernel: {132: "unsupported"}}}},+ showMessage: (message: string) => messages.push(message),+ fetchPost: () => assert.fail("unsupported replacement must not send a write request"),+ };+ runInNewContext(compiled, context);+ const element = {querySelector: () => assert.fail("unsupported replacement must not access results")};+ if (path.includes("mobile")) {+ context.replace(element, {method}, isAll);+ } else {+ context.replace(element, {method}, undefined, isAll);+ }+ assert.deepEqual(messages, ["unsupported"]);+ });+ }+ }+}diff --git a/kernel/api/contract_search_replace_test.go b/kernel/api/contract_search_replace_test.gonew file mode 100644index 0000000000..d2e8b5a049--- /dev/null+++ b/kernel/api/contract_search_replace_test.go@@ -0,0 +1,51 @@+package api++import (+ "encoding/json"+ "fmt"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractSearchReplaceMethods(t *testing.T) {+ previousConf, previousLangs, previousReadOnly := model.Conf, util.Langs, util.ReadOnly+ model.Conf = model.NewAppConf()+ model.Conf.Lang = "en"+ util.Langs = map[string]map[int]string{"en": {132: "unsupported replacement"}}+ util.ReadOnly = false+ t.Cleanup(func() { model.Conf, util.Langs, util.ReadOnly = previousConf, previousLangs, previousReadOnly })+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator) })+ const path = "/api/search/findReplace"+ engine.POST(path, model.CheckAdminRole, model.CheckReadonly, findReplace)+ for _, method := range []string{"null", "0", "1", "2", "3", "4", "4.9"} {+ for _, ids := range []string{`[]`, `["20261008120000-abcdefg"]`} {+ t.Run(method+"/"+ids, func(t *testing.T) {+ body := fmt.Sprintf(`{"k":"same","r":"same","ids":%s,"method":%s}`, ids, method)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(body)))+ requireAPIContract(t, "POST", path, recorder)+ var response struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data json.RawMessage `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if method == "2" || method == "4" || method == "4.9" {+ if response.Code != 1 || response.Msg != model.Conf.Language(132) || string(response.Data) != `{"closeTimeout":5000}` {+ t.Fatalf("unsupported method must return the existing error envelope: %s", recorder.Body.String())+ }+ } else if response.Code != 0 || string(response.Data) != "null" {+ t.Fatalf("supported unchanged replacement must remain a no-op: %s", recorder.Body.String())+ }+ })+ }+ }+}diff --git a/kernel/apicontract/search_query.go b/kernel/apicontract/search_query.goindex a1346d1ba2..4d3ed882c5 100644--- a/kernel/apicontract/search_query.go+++ b/kernel/apicontract/search_query.go@@ -66,6 +66,8 @@ type FullTextSearchBlockData struct {}type FindReplaceRequest struct {+ // Method 缺省或为 null 时使用文本替换;支持文本(0)、查询语法(1)和正则表达式(3)。+ // SQL(2)和语义搜索(4)返回 code=1 与提示信息,不执行替换;IDs 为空时表示替换全部。SearchBlockRequestK string `json:"k"`R string `json:"r"`diff --git a/kernel/model/search.go b/kernel/model/search.goindex 4e68fd9838..749b22fe9c 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -631,8 +631,9 @@ func FindReplace(keyword, replacement string, replaceTypes map[string]bool, ids// FindReplaceInBox 与 FindReplace 一致,但按 boxID 路由到加密 db 或全局 db。func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool, ids []string, paths, boxes []string, types, subTypes map[string]bool, method int, boxID string) (err error) {- // method:0:文本,1:查询语法,2:SQL,3:正则表达式- if 2 == method {+ // method:0:文本,1:查询语法,2:SQL,3:正则表达式,4:语义搜索。+ // SQL 和语义搜索不支持替换,必须在查询目标和生成历史前拒绝。+ if 2 == method || 4 == method {err = errors.New(Conf.Language(132))return}diff --git a/kernel/model/search_replace_test.go b/kernel/model/search_replace_test.gonew file mode 100644index 0000000000..04e38d3647--- /dev/null+++ b/kernel/model/search_replace_test.go@@ -0,0 +1,29 @@+package model++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestFindReplaceRejectsUnsupportedMethods(t *testing.T) {+ previousConf, previousLangs := Conf, util.Langs+ Conf = NewAppConf()+ Conf.Lang = "en"+ util.Langs = map[string]map[int]string{"en": {132: "unsupported replacement"}}+ t.Cleanup(func() { Conf, util.Langs = previousConf, previousLangs })+ for _, method := range []int{2, 4} {+ for _, ids := range [][]string{nil, {"20261008120000-abcdefg"}} {+ for _, boxID := range []string{"", "20261008120000-box0001"} {+ if err := FindReplaceInBox("same", "same", nil, ids, nil, nil, nil, nil, method, boxID); err == nil || err.Error() != Conf.Language(132) {+ t.Fatalf("method %d, ids %v, box %q: expected unsupported replacement, got %v", method, ids, boxID, err)+ }+ }+ }+ }+ for _, method := range []int{0, 1, 3} {+ if err := FindReplace("same", "same", nil, nil, nil, nil, nil, nil, method, 0, 0); err != nil {+ t.Fatalf("method %d: unchanged replacement must remain a no-op: %v", method, err)+ }+ }+}