Skip to content

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

:sparkles: per-box SQLCipher database for encrypted notebooks (stage 5) #18034

Daniel815900989cee
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 62025ff510..0890c58043 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -27,6 +27,7 @@ import (
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -120,6 +121,10 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error
if err != nil {
return err
}
+ // 先打开加密 db,成功后再缓存 DEK(保证两者一致:DEK 在内存 ⟺ 加密 db 已打开)
+ if err = sql.OpenEncryptedDB(boxID, dek); err != nil {
+ return err
+ }
cachedDEKsLock.Lock()
cachedDEKs[boxID] = dek
cachedDEKsLock.Unlock()
@@ -134,7 +139,7 @@ func IsBoxUnlocked(boxID string) bool {
return ok
}
-// LockBox 清除指定笔记本的 DEK。Unmount 单个加密笔记本或手动锁定时调用。
+// LockBox 清除指定笔记本的 DEK 并关闭其加密 db。Unmount 单个加密笔记本或手动锁定时调用。
// 同时清除该笔记本的 TreeData 缓存,避免明文树数据在内存中残留。
func LockBox(boxID string) {
cachedDEKsLock.Lock()
@@ -143,6 +148,7 @@ func LockBox(boxID string) {
delete(cachedDEKs, boxID)
}
cachedDEKsLock.Unlock()
+ sql.CloseEncryptedDB(boxID)
cache.ClearTreeCache()
}
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 7162d25c99..e5ce616279 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -20,6 +20,7 @@ import (
"bytes"
"crypto/sha256"
"database/sql"
+ "encoding/hex"
"errors"
"fmt"
"os"
@@ -53,6 +54,10 @@ var (
assetContentDB *sql.DB
initDatabaseLock = sync.RWMutex{}
+
+ // encryptedDBs 维护已打开的加密笔记本独立 db 连接,按 boxID 索引。
+ // UnlockBox 时打开并注册,LockBox/Unmount 时关闭并移除。
+ encryptedDBs = &sync.Map{} // boxID -> *sql.DB
)
func init() {
@@ -1779,3 +1784,96 @@ func vacuum() {
}
}
}
+
+// OpenEncryptedDB 打开加密笔记本的独立 SQLCipher db 并注册到 encryptedDBs。
+// dek 是该 box 的 32 字节数据密钥;DSN 用 SQLCipher 原始 key 格式 x'<hex>',避免 SQLCipher 再做 KDF。
+// 首次打开会建表(幂等 IF NOT EXISTS)。UnlockBox 时调用。
+func OpenEncryptedDB(boxID string, dek []byte) (err error) {
+ if _, loaded := encryptedDBs.Load(boxID); loaded {
+ return nil // 已打开
+ }
+ dbPath := util.EncryptedDBPath(boxID)
+ // SQLCipher DSN:_key=x'<hex>' 让 go-sqlite3 执行 PRAGMA key;其余 PRAGMA 与全局 siyuan.db 对齐
+ dsn := dbPath + "?_journal_mode=WAL&_synchronous=OFF&_mmap_size=4294967296&_secure_delete=OFF" +
+ "&_cache_size=-128000&_page_size=32768&_busy_timeout=7000&_ignore_check_constraints=ON" +
+ "&_temp_store=MEMORY&_case_sensitive_like=OFF&_key=x'" + hex.EncodeToString(dek) + "'"
+ boxDB, err := sql.Open("sqlite3_extended", dsn)
+ if err != nil {
+ return err
+ }
+ boxDB.SetMaxOpenConns(20)
+ boxDB.SetMaxIdleConns(4)
+ if err = initEncryptedDBTables(boxDB); err != nil {
+ boxDB.Close()
+ return err
+ }
+ encryptedDBs.Store(boxID, boxDB)
+ return nil
+}
+
+// CloseEncryptedDB 关闭并移除加密笔记本的 db 连接。LockBox/Unmount 时调用。
+func CloseEncryptedDB(boxID string) {
+ if v, ok := encryptedDBs.LoadAndDelete(boxID); ok {
+ if boxDB, ok := v.(*sql.DB); ok {
+ boxDB.Close()
+ }
+ }
+}
+
+// GetEncryptedDB 返回加密 box 的 db 句柄;未打开返回 nil。
+func GetEncryptedDB(boxID string) *sql.DB {
+ if v, ok := encryptedDBs.Load(boxID); ok {
+ if boxDB, ok := v.(*sql.DB); ok {
+ return boxDB
+ }
+ }
+ return nil
+}
+
+// RemoveEncryptedDBFile 关闭连接并删除加密 db 文件(含 WAL/SHM)。删除笔记本时调用。
+func RemoveEncryptedDBFile(boxID string) {
+ CloseEncryptedDB(boxID)
+ dbPath := util.EncryptedDBPath(boxID)
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ if err := os.Remove(dbPath + suffix); err != nil && !os.IsNotExist(err) {
+ logging.LogErrorf("remove encrypted db file [%s] failed: %s", dbPath+suffix, err)
+ }
+ }
+}
+
+// beginTxForBox 按 box 选 db 开事务。加密 box 用其独立 db,否则用全局 db。
+func beginTxForBox(box string) (tx *sql.Tx, err error) {
+ if boxDB := GetEncryptedDB(box); boxDB != nil {
+ if tx, err = boxDB.Begin(); err != nil {
+ logging.LogErrorf("begin tx (encrypted box %s) failed: %s\n %s", box, err, logging.ShortStack())
+ return
+ }
+ return
+ }
+ return beginTx()
+}
+
+// initEncryptedDBTables 在加密 box db 上建内容表(幂等)。结构与全局 siyuan.db 的内容表一致,
+// 但不含 stat 表(加密 db 不参与版本管理)。首次打开时调用。
+func initEncryptedDBTables(boxDB *sql.DB) (err error) {
+ tables := []string{
+ "CREATE TABLE IF NOT EXISTS blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated)",
+ "CREATE TABLE IF NOT EXISTS spans (id, block_id, root_id, box, path, content, markdown, type, ial)",
+ "CREATE TABLE IF NOT EXISTS assets (id, block_id, root_id, box, docpath, path, name, title, hash)",
+ "CREATE TABLE IF NOT EXISTS attributes (id, name, value, type, block_id, root_id, box, path)",
+ "CREATE TABLE IF NOT EXISTS refs (id, def_block_id, def_block_parent_id, def_block_root_id, def_block_path, block_id, root_id, box, path, content, markdown, type)",
+ "CREATE TABLE IF NOT EXISTS file_annotation_refs (id, file_path, annotation_id, block_id, root_id, box, path, content, type)",
+ "CREATE TABLE IF NOT EXISTS block_embeddings (id TEXT PRIMARY KEY, root_id TEXT, box TEXT, path TEXT, embedding BLOB, model TEXT, content_len INTEGER, updated TEXT, fail_count INTEGER NOT NULL DEFAULT 0, last_tried INTEGER NOT NULL DEFAULT 0, ignored_type INTEGER NOT NULL DEFAULT 0)",
+ }
+ for _, stmt := range tables {
+ if _, err = boxDB.Exec(stmt); err != nil {
+ return
+ }
+ }
+ // FTS5 external-content 虚拟表,tokenize 与全局保持一致(siyuan 分词器)
+ ftsStmt := "CREATE VIRTUAL TABLE IF NOT EXISTS blocks_fts USING fts5(id UNINDEXED, parent_id UNINDEXED, root_id UNINDEXED, hash UNINDEXED, box UNINDEXED, path UNINDEXED, hpath UNINDEXED, name, alias, memo, tag, content, fcontent, markdown UNINDEXED, length UNINDEXED, type UNINDEXED, subtype UNINDEXED, ial, sort UNINDEXED, created UNINDEXED, updated UNINDEXED, content='blocks', content_rowid='rowid', tokenize=\"" + ftsTokenize() + "\")"
+ if _, err = boxDB.Exec(ftsStmt); err != nil {
+ return
+ }
+ return
+}
diff --git a/kernel/sql/queue.go b/kernel/sql/queue.go
index a9897ae287..79b12cf38c 100644
--- a/kernel/sql/queue.go
+++ b/kernel/sql/queue.go
@@ -56,6 +56,30 @@ type dbQueueOperation struct {
removeAssetHashes []string // delete_assets
}
+// boxID 从 op 提取目标 boxID,供 beginTxForBox 路由到加密 db 或全局 db。
+// delete_id/delete_ids/delete_assets/index_node 无 box 上下文,返回空串 → 走全局 db。
+func (op *dbQueueOperation) boxID() string {
+ switch op.action {
+ case "index", "rename", "move":
+ if op.indexTree != nil {
+ return op.indexTree.Box
+ }
+ case "upsert", "update_refs", "delete_refs":
+ if op.upsertTree != nil {
+ return op.upsertTree.Box
+ }
+ case "delete":
+ return op.removeTreeBox
+ case "delete_box", "delete_box_refs":
+ return op.box
+ case "update_block_content":
+ if op.block != nil {
+ return op.block.Box
+ }
+ }
+ return ""
+}
+
func FlushTxJob() {
task.AppendTask(task.DatabaseIndexCommit, FlushQueue)
}
@@ -164,7 +188,7 @@ func FlushQueue() {
return
}
- tx, err := beginTx()
+ tx, err := beginTxForBox(op.boxID())
if err != nil {
return
}
@@ -257,9 +281,15 @@ func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err error
tx.Exec("UPDATE block_embeddings SET box = ?, path = ? WHERE root_id = ?", op.indexTree.Box, op.indexTree.Path, op.indexTree.ID)
}
case "delete_box":
- err = deleteByBoxTx(tx, op.box)
- if nil == err {
- tx.Exec("DELETE FROM block_embeddings WHERE box = ?", op.box)
+ // 加密 box 的数据在独立库,deleteByBoxTx(删全局库 WHERE box=?)对其无意义。
+ // 加密 box 关闭时由 model 层的 CloseEncryptedDB 处理(关库连接),这里跳过全局库删除。
+ if GetEncryptedDB(op.box) != nil {
+ err = nil // 加密 box:不删全局库(数据不在那里)
+ } else {
+ err = deleteByBoxTx(tx, op.box)
+ if nil == err {
+ tx.Exec("DELETE FROM block_embeddings WHERE box = ?", op.box)
+ }
}
case "delete_box_refs":
err = deleteRefsByBoxTx(tx, op.box)
@@ -513,7 +543,7 @@ func processDiskQueue() {
if nil == op {
continue
}
- tx, err := beginTx()
+ tx, err := beginTxForBox(op.boxID())
if err != nil {
return
}
diff --git a/kernel/util/working.go b/kernel/util/working.go
index a2970bf6d9..51880380ed 100644
--- a/kernel/util/working.go
+++ b/kernel/util/working.go
@@ -599,6 +599,12 @@ func GetDataAssetsAbsPath() (ret string) {
return
}
+// EncryptedDBPath 返回加密笔记本的独立 SQLCipher db 文件路径。
+// 与 siyuan.db 同放 temp 目录,文件名带 boxID 区分多个加密笔记本。db 是可重建的索引,非原始内容。
+func EncryptedDBPath(boxID string) string {
+ return filepath.Join(TempDir, "siyuan-encrypted-"+boxID+".db")
+}
+
func tryLockWorkspace() {
WorkspaceLock = flock.New(filepath.Join(WorkspaceDir, ".lock"))
ok, err := WorkspaceLock.TryLock()