Skip to content

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

:bug: Prevent duplicate block IDs when pasting in encrypted notebooks

Daniel3b067cc4d4b0
diff --git a/app/src/protyle/util/pasteIdentity.test.ts b/app/src/protyle/util/pasteIdentity.test.ts
new file mode 100644
index 0000000000..ed7b88e44a
--- /dev/null
+++ b/app/src/protyle/util/pasteIdentity.test.ts
@@ -0,0 +1,158 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+// 执行完整粘贴入口及真实 DOM,检查内核存在性结果对复制、剪切和失败中止的影响。
+const browserCases = async (sources: Record<string, string>, lutePath: string) => {
+ const check = require("node:assert/strict");
+ require(lutePath);
+ const constants = {Constants: {ZWSP: "\u200b", CUSTOM_RIFF_DECKS: "custom-riff-decks"}};
+ const load = (source: string, mocks: Record<string, unknown>) => {
+ const api = {};
+ new Function("exports", "require", source)(api, (id: string) => mocks[id] || {});
+ return api;
+ };
+ const clear = load(sources.clear, {
+ "../../constants": constants,
+ "../wysiwyg/blockSelection": {BLOCK_SELECTION_MODE_CLASS: "protyle-wysiwyg--block-select"},
+ });
+ const pasteSource = load(sources.pasteSource, {});
+ const tabsCopy = load(sources.tabsCopy, {});
+ const originalID = "20261007000000-abcdefg";
+ const childID = "20261007000001-abcdefg";
+ const html = `<div data-node-id="${originalID}" data-type="NodeBlockquote" class="bq protyle-wysiwyg--select" refcount="2">` +
+ `<div data-node-id="${childID}" data-type="NodeParagraph" class="p" refcount="1">` +
+ '<div contenteditable="true">Original content</div></div></div>';
+ for (const mode of ["copy", "cut", "mixed", "error", "target removed"]) {
+ const editor = document.createElement("div");
+ editor.innerHTML = html + '<div data-node-id="20261007000002-abcdefg" data-type="NodeParagraph" class="p">' +
+ '<div contenteditable="true">Target</div></div>';
+ document.body.append(editor);
+ const original = editor.firstElementChild;
+ const originalHTML = original.outerHTML;
+ const target = editor.lastElementChild as HTMLElement;
+ if (mode === "cut" || mode === "mixed") {
+ original.remove();
+ if (mode === "mixed") {
+ target.before(original.querySelector("[data-node-id]").cloneNode(true));
+ }
+ }
+ const range = document.createRange();
+ range.selectNodeContents(target.firstElementChild);
+ range.collapse(false);
+ const requests: {ids: string[]}[] = [];
+ const inserted: string[] = [];
+ let available = true;
+ const mocks: Record<string, unknown> = {
+ "../../constants": constants,
+ "../../util/pathName": {isEncryptedBox: () => true},
+ "./pasteAssets": {preparePasteAssets: async (_box: string, value: string) => value},
+ "./pasteSource": pasteSource,
+ "./clear": clear,
+ "./tabsCopy": tabsCopy,
+ "../render/listMindmap/model": {remapListMindmapIDs: () => {}},
+ "../render/embedRenderState": {resetPastedQueryEmbedRenderState: () => {}},
+ "./inlineElementMarker": {normalizeSemanticInlineElements: () => {},
+ stripSemanticMarkersFromRangeText: () => ""},
+ "../runtimeCapabilities": {getProtyleBlockDOMSanitizer: (): undefined => undefined,
+ areProtylePluginExtensionsEnabled: () => false},
+ "../upload/insertPosition": {
+ createUploadInsertPosition: () => ({range}), captureUploadDocument: () => ({}),
+ isUploadInsertPositionAvailable: () => available,
+ getAvailableUploadInsertRange: () => available ? range : undefined,
+ },
+ "./selection": {getEditorRange: () => range},
+ "./hasClosest": {hasClosestBlock: (item: Node) =>
+ (item.nodeType === Node.ELEMENT_NODE ? item as Element : item.parentElement)?.closest("[data-node-id]")},
+ "./compatibility": {isInHarmony: () => false},
+ "./officeMath": {extractOfficeMathHTML: () => ""},
+ "./processCode": {processPasteCode: () => "", processRender: () => {}},
+ "../ui/hideElements": {hideElements: () => {}},
+ "../render/blockRender": {blockRender: () => {}},
+ "../render/highlightRender": {highlightRender: () => {}},
+ "../render/av/render": {avRender: () => {}},
+ "../../util/highlightById": {scrollCenter: () => {}},
+ "dayjs": () => ({format: () => "20261007000003"}),
+ "../../util/fetch": {fetchSyncPost: async (url: string, request: {ids: string[]}) => {
+ check.equal(url, "/api/block/checkBlocksExist");
+ requests.push(request);
+ if (mode === "target removed") {
+ available = false;
+ }
+ return {code: mode === "error" ? -1 : 0, data: {
+ [originalID]: mode === "copy", [childID]: mode === "copy" || mode === "mixed",
+ }};
+ }},
+ "./insertHTML": {insertHTML: (value: string) => {
+ inserted.push(value);
+ target.insertAdjacentHTML("beforebegin", value);
+ }},
+ };
+ const api = load(sources.paste, mocks) as typeof import("./paste");
+ const protyle = {notebookId: "encrypted-notebook", hint: {enableExtend: false},
+ wysiwyg: {element: editor}, toolbar: {getCurrentType: (): string[] => []}, lute: Lute.New()} as unknown as IProtyle;
+ await api.paste(protyle, {target, textPlain: "Original content", textHTML: "", siyuanHTML: html});
+ check.deepEqual(requests, [{ids: [originalID, childID]}]);
+ check.equal(original.outerHTML, originalHTML);
+ if (mode === "error" || mode === "target removed") {
+ check.equal(inserted.length, 0);
+ } else {
+ check.equal(inserted.length, 1);
+ const pasted = target.previousElementSibling;
+ const pastedChild = pasted.querySelector("[data-node-id]");
+ if (mode === "copy") {
+ check.notEqual(pasted.getAttribute("data-node-id"), originalID);
+ check.notEqual(pastedChild.getAttribute("data-node-id"), childID);
+ check.equal(new Set(Array.from(editor.querySelectorAll("[data-node-id]"), item =>
+ item.getAttribute("data-node-id"))).size, 5);
+ check.equal(pasted.hasAttribute("refcount"), false);
+ pastedChild.querySelector("[contenteditable]").textContent = "Edited copy";
+ check.equal(original.textContent, "Original content");
+ } else {
+ check.equal(pasted.getAttribute("data-node-id"), originalID);
+ check.equal(pasted.getAttribute("refcount"), "2");
+ check.equal(pastedChild.getAttribute("data-node-id") === childID, mode === "cut");
+ const ids = Array.from(editor.querySelectorAll("[data-node-id]"), item => item.getAttribute("data-node-id"));
+ check.equal(new Set(ids).size, ids.length);
+ }
+ }
+ editor.remove();
+ }
+ return "paste-identity-ok";
+};
+
+test("internal block paste keeps copied IDs independent and preserves cut IDs in the real DOM", {timeout: 30000}, async () => {
+ const directory = mkdtempSync(path.join(tmpdir(), "siyuan-paste-identity-"));
+ const sources = Object.fromEntries(["paste", "clear", "pasteSource", "tabsCopy"].map(name => [name,
+ transpileModule(readFileSync(`src/protyle/util/${name}.ts`, "utf8"), {
+ compilerOptions: {target: ScriptTarget.ES2022, module: ModuleKind.CommonJS},
+ }).outputText]));
+ const execute = transpileModule(`const __name = (value) => value; (${browserCases.toString()})(${JSON.stringify(sources)},
+ ${JSON.stringify(path.resolve("stage/protyle/js/lute/lute.min.js"))})`, {
+ compilerOptions: {target: ScriptTarget.ES2022},
+ }).outputText;
+ const script = path.join(directory, "main.cjs");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ try {
+ await win.loadURL("about:blank");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(execute)}));
+ app.exit(0);
+ } catch (error) { console.error(error); app.exit(1); }
+});`);
+ try {
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script, "--no-sandbox"],
+ {env, timeout: 25000});
+ assert.match(result.stdout, /paste-identity-ok/);
+ } finally {
+ rmSync(directory, {recursive: true, force: true});
+ }
+});
diff --git a/kernel/api/block.go b/kernel/api/block.go
index 7bfc9dcaf6..ba1e34e569 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -344,7 +344,18 @@ var checkBlocksExist = contractHandler(apicontract.CheckBlocksExist, func(c *gin
return apicontract.Failure[map[string]bool](-1, err.Error())
}
ids = filterBlockIDsByPublishAccess(c, ids, boxID)
- return apicontract.Success(treenode.ExistBlockTreesInBox(ids, boxID))
+ existing := treenode.ExistBlockTreesInBox(ids, boxID)
+ if boxID == "" {
+ // 隐式批量查询仅合并已持有响应租约的加密库,避免读取随后解锁但未取得租约的笔记本。
+ for _, leasedBoxID := range requestBoxLeases(c) {
+ for id, exists := range treenode.ExistBlockTreesInBox(ids, leasedBoxID) {
+ if exists {
+ existing[id] = true
+ }
+ }
+ }
+ }
+ return apicontract.Success(existing)
})
var getDocInfo = contractHandler(apicontract.GetDocInfo, func(c *gin.Context, request apicontract.BlockQueryRequest) apicontract.Response[*apicontract.DocInfo] {
diff --git a/kernel/api/box_lease_test.go b/kernel/api/box_lease_test.go
index 0267d8fe38..4a6aec24a3 100644
--- a/kernel/api/box_lease_test.go
+++ b/kernel/api/box_lease_test.go
@@ -145,6 +145,18 @@ func TestContractBatchIndexesNotebookResponseLease(t *testing.T) {
runNotebookResponseLease(t, false, true)
}
+func TestContractCheckBlocksExistNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, false, false)
+}
+
+func TestContractCheckBlocksExistExplicitNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, true, false)
+}
+
+func TestContractCheckBlocksExistBatchNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, false, true)
+}
+
func runNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
t.Helper()
if os.Getenv("SIYUAN_TEST_NOTEBOOK_RESPONSE_LEASE") == t.Name() {
@@ -239,6 +251,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
engine.POST("/api/block/getBlockInfo", getBlockInfo)
engine.POST("/api/block/getBlockSiblingID", getBlockSiblingID)
engine.POST("/api/block/getBlocksIndexes", getBlocksIndexes)
+ engine.POST("/api/block/checkBlocksExist", checkBlocksExist)
engine.POST("/review/blockSwapLease", func(c *gin.Context) {
tx := &model.Transaction{DoOperations: []*model.Operation{{Action: "swapBlockRef"}}}
if err := holdBlockSwapReplayRequests(c, tx, boxIDs); err != nil {
@@ -306,6 +319,10 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
endpoint, typedQuery = "/api/block/getBlockSiblingID", true
case "TestContractBatchIndexesNotebookResponseLease":
endpoint, typedQuery = "/api/block/getBlocksIndexes", true
+ case "TestContractCheckBlocksExistNotebookResponseLease", "TestContractCheckBlocksExistExplicitNotebookResponseLease", "TestContractCheckBlocksExistBatchNotebookResponseLease":
+ endpoint, typedQuery = "/api/block/checkBlocksExist", true
+ delete(args, "id")
+ args["ids"] = boxIDs
}
requestBody, err := json.Marshal(args)
if err != nil {
@@ -326,6 +343,20 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
<-responseDone
t.Fatalf("fixture did not produce plaintext: %s", body)
}
+ if endpoint == "/api/block/checkBlocksExist" {
+ var response struct {
+ Code int `json:"code"`
+ Data map[string]bool `json:"data"`
+ }
+ if err := json.Unmarshal(body, &response); err != nil || response.Code != 0 {
+ t.Fatalf("existence query failed: %s, %v", body, err)
+ }
+ for _, boxID := range boxIDs {
+ if !response.Data[boxID] {
+ t.Fatalf("unlocked notebook block was not found: %s", body)
+ }
+ }
+ }
lockDone := make(chan string, len(boxIDs))
for _, boxID := range boxIDs {
go func() { model.LockBox(boxID); lockDone <- boxID }()
diff --git a/kernel/api/contract_block_existence_test.go b/kernel/api/contract_block_existence_test.go
new file mode 100644
index 0000000000..4a818c0b9c
--- /dev/null
+++ b/kernel/api/contract_block_existence_test.go
@@ -0,0 +1,138 @@
+//go:build (sqlcipher || libsqlcipher) && cgo
+
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractCheckBlocksExist(t *testing.T) {
+ const helper = "SIYUAN_TEST_BLOCK_EXISTENCE"
+ if os.Getenv(helper) != "1" {
+ // 使用独立进程隔离数据库、密钥及异步索引。
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAPIContractCheckBlocksExist$", "-test.v")
+ command.Env = append(os.Environ(), helper+"=1")
+ if output, err := command.CombinedOutput(); err != nil {
+ t.Fatalf("block existence subprocess failed: %v\n%s", err, output)
+ }
+ return
+ }
+ root := t.TempDir()
+ util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "temp"), filepath.Join(root, "conf"), filepath.Join(root, "history")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath, util.HistoryDBPath, util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, util.DBName), filepath.Join(util.TempDir, "history.db"), filepath.Join(util.TempDir, "asset_content.db"), filepath.Join(util.TempDir, "blocktree.db")
+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ model.Conf = model.NewAppConf()
+ model.Conf.NotebookCrypto, model.Conf.Sync, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()
+ model.Conf.Editor, model.Conf.Export, model.Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ defer sql.CloseDatabase()
+ if err := model.EnableEncryptedNotebook("existence-password"); err != nil {
+ t.Fatal(err)
+ }
+ var boxes []string
+ for range 2 {
+ boxID, err := model.CreateEncryptedBox("Block existence", "existence-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ boxes = append(boxes, boxID)
+ defer model.LockBox(boxID)
+ }
+ normalBox, normalID, encryptedID, cutID, missingID := ast.NewNodeID(), ast.NewNodeID(), ast.NewNodeID(), ast.NewNodeID(), ast.NewNodeID()
+ index := func(boxID, id string) {
+ t.Helper()
+ treenode.UpsertBlockTree(&parse.Tree{ID: id, Box: boxID, Path: "/" + id + ".sy", Root: &ast.Node{ID: id, Type: ast.NodeDocument}})
+ }
+ index(normalBox, normalID)
+ index(boxes[0], encryptedID)
+ index(boxes[0], cutID)
+ index(boxes[1], boxes[1])
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ engine.Use(boxLeaseMiddleware)
+ role := model.RoleAdministrator
+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role); c.Next() })
+ engine.POST("/api/block/checkBlocksExist", checkBlocksExist)
+ post := func(t *testing.T, ids any, notebook string, wantCode int, want map[string]bool) {
+ t.Helper()
+ args := map[string]any{"ids": ids}
+ if notebook != "" {
+ args["notebook"] = notebook
+ }
+ body, err := json.Marshal(args)
+ if err != nil {
+ t.Fatal(err)
+ }
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/block/checkBlocksExist", strings.NewReader(string(body))))
+ requireAPIContract(t, http.MethodPost, "/api/block/checkBlocksExist", recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data map[string]bool `json:"data"`
+ }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != wantCode || !reflect.DeepEqual(response.Data, want) {
+ t.Fatalf("existence query %s: %s, want code %d data %v, %v", body, recorder.Body.String(), wantCode, want, err)
+ }
+ }
+ t.Run("copy and mixed notebook batch", func(t *testing.T) {
+ post(t, []string{normalID, encryptedID, boxes[1], missingID, encryptedID}, "", 0,
+ map[string]bool{normalID: true, encryptedID: true, boxes[1]: true, missingID: false})
+ })
+ t.Run("explicit encrypted notebook", func(t *testing.T) {
+ post(t, []string{normalID, encryptedID, boxes[1], missingID}, boxes[0], 0,
+ map[string]bool{normalID: false, encryptedID: true, boxes[1]: false, missingID: false})
+ })
+ t.Run("ordinary notebook parameter compatibility", func(t *testing.T) {
+ post(t, []string{normalID, encryptedID}, normalBox, 0, map[string]bool{normalID: true, encryptedID: true})
+ })
+ t.Run("empty batch", func(t *testing.T) {
+ post(t, []string{}, "", 0, map[string]bool{})
+ })
+ t.Run("ignored values", func(t *testing.T) {
+ post(t, []any{nil, 42, true, "invalid", encryptedID}, "", 0, map[string]bool{encryptedID: true})
+ })
+ t.Run("cut block", func(t *testing.T) {
+ post(t, []string{cutID}, "", 0, map[string]bool{cutID: true})
+ treenode.RemoveBlockTree(boxes[0], cutID)
+ post(t, []string{cutID}, "", 0, map[string]bool{cutID: false})
+ })
+ t.Run("publish reader", func(t *testing.T) {
+ role = model.RoleReader
+ defer func() { role = model.RoleAdministrator }()
+ post(t, []string{normalID, encryptedID, boxes[1]}, "", 0, map[string]bool{normalID: true})
+ post(t, []string{encryptedID}, boxes[0], 0, map[string]bool{})
+ })
+ t.Run("locked notebook", func(t *testing.T) {
+ model.LockBox(boxes[0])
+ post(t, []string{normalID, encryptedID, boxes[1]}, "", 0, map[string]bool{normalID: true, encryptedID: false, boxes[1]: true})
+ post(t, []string{encryptedID}, boxes[0], -1, nil)
+ })
+}
diff --git a/kernel/apicontract/block.go b/kernel/apicontract/block.go
index 3d16b97514..49af8ae73c 100644
--- a/kernel/apicontract/block.go
+++ b/kernel/apicontract/block.go
@@ -13,6 +13,10 @@ type TailChildBlocksRequest struct {
N *float64 `json:"n" api:"optional"`
}
+// CheckBlocksExistRequest 批量查询有效块 ID,忽略非字符串及不符合块 ID 格式的值,重复 ID 合并为一个结果。
+// notebook 为加密笔记本时只查询该库;省略或传入普通笔记本时查询全局库及本请求已持有租约的加密库。
+// 不存在或已锁定且无法确定归属的块返回 false;显式指定已锁定的加密笔记本返回错误。
+// 发布读者的不可访问块不返回结果,加密响应租约保持到响应发送完成。
type CheckBlocksExistRequest struct {
IDs []JSONValue `json:"ids"`
Notebook string `json:"notebook" api:"optional,nullable,ignoretype"`
diff --git a/kernel/apicontract/block_existence_test.go b/kernel/apicontract/block_existence_test.go
new file mode 100644
index 0000000000..3fb9415011
--- /dev/null
+++ b/kernel/apicontract/block_existence_test.go
@@ -0,0 +1,27 @@
+package apicontract
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestCheckBlocksExistInputCompatibility(t *testing.T) {
+ for _, body := range []string{"", "null", "{}", `{"ids":null}`, `{"ids":"invalid"}`} {
+ if _, err := CheckBlocksExist.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("invalid batch accepted: %q", body)
+ }
+ }
+ for _, notebook := range []string{"null", "42", "true", `""`} {
+ request, err := CheckBlocksExist.Decode(strings.NewReader(`{"ids":[],"notebook":` + notebook + `,"id":false}`))
+ if err != nil || request.IDs == nil || request.Notebook != "" || request.ID != "" {
+ t.Fatalf("ignored optional values changed: %+v, %v", request, err)
+ }
+ }
+ request, err := CheckBlocksExist.Decode(strings.NewReader(`{"ids":["20261007000000-abcdefg",null,42,true,"invalid"],"notebook":"20261007000001-abcdefg"}`))
+ if err != nil || len(request.IDs) != 5 || request.Notebook != "20261007000001-abcdefg" {
+ t.Fatalf("mixed batch compatibility changed: %+v, %v", request, err)
+ }
+ if id, ok := request.IDs[0].StringValue(); !ok || id != "20261007000000-abcdefg" {
+ t.Fatalf("block ID changed: %q, %v", id, ok)
+ }
+}