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 custom kernel home directory https://github.com/siyuan-note/siyuan/issues/19994
Daniel51f942cd8e28
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex 9cdef3cea2..85dfb8dca0 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -61,6 +61,10 @@ Note: In the development environment, the kernel process will not be automatical* Windows: `./SiYuan-Kernel.exe serve --mode=dev`* Linux/macOS: `./SiYuan-Kernel serve --mode=dev`+The optional global `--home-dir <path>` flag sets the base directory for user configuration. Files such as the workspace registry and cookie key remain under `<path>/.config/siyuan/`. Relative paths are resolved against the current process directory, and missing configuration directories are created. Invalid or unwritable paths fail without falling back to the system user home. Omitting the flag preserves the existing behavior. The flag also applies to offline CLI commands such as `workspace list`.++Use `--workspace` for notebook data and `--wd` for application resources independently. For example, after creating an empty `/work/siyuan-workspace` directory: `./SiYuan-Kernel serve --mode=dev --home-dir=/work/siyuan-home --workspace=/work/siyuan-workspace --wd=/work/siyuan/app`. When starting the server without an explicit workspace or a registered workspace in the selected profile, the default workspace remains under the selected home directory using the platform's existing layout (`SiYuan` on Windows/Linux, `Library/Application Support/SiYuan` on macOS). When `--home-dir` is set on Windows, `USERPROFILE` does not override it. These options do not change the mobile app's sandbox paths.+### iOS* `cd kernel`diff --git a/.github/CONTRIBUTING.zh-CN.md b/.github/CONTRIBUTING.zh-CN.mdindex bf75a7709f..29794df73d 100644--- a/.github/CONTRIBUTING.zh-CN.md+++ b/.github/CONTRIBUTING.zh-CN.md@@ -61,6 +61,10 @@ NPM 镜像:* Windows: `./SiYuan-Kernel.exe serve --mode=dev`* Linux/macOS: `./SiYuan-Kernel serve --mode=dev`+可选的全局参数 `--home-dir <path>` 用于指定用户配置目录的基路径。工作空间列表、Cookie 密钥等文件仍保存在 `<path>/.config/siyuan/` 中。相对路径以进程当前目录为基准解析,缺失的配置目录会自动创建;路径无效或不可写时直接报错,不会回退到系统用户主目录。未指定该参数时保持现有行为。该参数也适用于 `workspace list` 等离线 CLI 命令。++笔记数据目录由 `--workspace` 指定,应用资源目录由 `--wd` 指定,三者可以独立使用。例如,先创建空目录 `/work/siyuan-workspace`,再执行:`./SiYuan-Kernel serve --mode=dev --home-dir=/work/siyuan-home --workspace=/work/siyuan-workspace --wd=/work/siyuan/app`。启动服务时未显式指定工作空间且所选配置中没有已注册工作空间,默认工作空间沿用各平台的目录布局,位于所选主目录下:Windows/Linux 为 `SiYuan`,macOS 为 `Library/Application Support/SiYuan`。Windows 上显式指定 `--home-dir` 后,`USERPROFILE` 不再覆盖该选择。这些选项不改变移动端应用的沙箱路径。+### iOS* `cd kernel`diff --git a/kernel/cli/cmd/home_test.go b/kernel/cli/cmd/home_test.gonew file mode 100644index 0000000000..c6c3502905--- /dev/null+++ b/kernel/cli/cmd/home_test.go@@ -0,0 +1,104 @@+// SiYuan - From thought to insight, with agents+// 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.++package cmd++import (+ "encoding/json"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestHomeDirCLI(t *testing.T) {+ home := t.TempDir()+ registered := filepath.Join(t.TempDir(), "registered-workspace")+ if err := os.MkdirAll(registered, 0755); err != nil {+ t.Fatal(err)+ }+ confDir := filepath.Join(home, ".config", "siyuan")+ if err := os.MkdirAll(confDir, 0755); err != nil {+ t.Fatal(err)+ }+ data, _ := json.Marshal([]string{registered})+ if err := os.WriteFile(filepath.Join(confDir, "workspace.json"), data, 0600); err != nil {+ t.Fatal(err)+ }+ for _, command := range []string{"list", "info"} {+ t.Run(command, func(t *testing.T) {+ process := exec.Command(os.Args[0], "-test.run=^TestHomeDirCLIProcess$", "--",+ "--home-dir="+home, "workspace", command)+ process.Env = append(os.Environ(), "SIYUAN_TEST_HOME_CLI=1", "SIYUAN_WORKSPACE_PATH=")+ output, err := process.CombinedOutput()+ if err != nil || !strings.Contains(string(output), registered) {+ t.Fatalf("workspace %s ignored --home-dir: %v\n%s", command, err, output)+ }+ })+ }+}++func TestHomeDirServeFlag(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_HOME_SERVE_FLAG") == "" {+ process := exec.Command(os.Args[0], "-test.run=^TestHomeDirServeFlag$")+ process.Env = append(os.Environ(), "SIYUAN_TEST_HOME_SERVE_FLAG=1")+ if output, err := process.CombinedOutput(); err != nil {+ t.Fatalf("serve home flag check failed: %v\n%s", err, output)+ }+ return+ }+ oldHome, oldPath, oldWorkspace, oldWd := util.HomeDir, homeDirPath, workspacePath, serveWdPath+ homeFlag := rootCmd.PersistentFlags().Lookup("home-dir")+ workspaceFlag := rootCmd.PersistentFlags().Lookup("workspace")+ wdFlag := serveCmd.Flags().Lookup("wd")+ oldHomeChanged, oldWorkspaceChanged, oldWdChanged := homeFlag.Changed, workspaceFlag.Changed, wdFlag.Changed+ t.Cleanup(func() {+ util.HomeDir, homeDirPath, workspacePath, serveWdPath = oldHome, oldPath, oldWorkspace, oldWd+ homeFlag.Changed, workspaceFlag.Changed, wdFlag.Changed = oldHomeChanged, oldWorkspaceChanged, oldWdChanged+ })+ home, workspace, wd := t.TempDir(), t.TempDir(), t.TempDir()+ if err := serveCmd.ParseFlags([]string{"--home-dir=" + home, "--workspace=" + workspace, "--wd=" + wd}); err != nil {+ t.Fatal(err)+ }+ if err := serveCmd.PersistentPreRunE(serveCmd, nil); err != nil {+ t.Fatal(err)+ }+ if util.HomeDir != home || workspacePath != workspace || serveWdPath != wd {+ t.Fatalf("flags were not kept independent: home=%q, workspace=%q, wd=%q", util.HomeDir, workspacePath, serveWdPath)+ }+ file := filepath.Join(t.TempDir(), "not-a-directory")+ if err := os.WriteFile(file, []byte("keep"), 0600); err != nil {+ t.Fatal(err)+ }+ homeDirPath = file+ if err := serveCmd.PersistentPreRunE(serveCmd, nil); err == nil {+ t.Fatal("serve accepted an invalid home before boot")+ }+ if util.HomeDir != home {+ t.Fatal("invalid home changed the active profile")+ }+}++// TestHomeDirCLIProcess 在独立测试进程中执行离线命令,不启动内核服务。+func TestHomeDirCLIProcess(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_HOME_CLI") == "" {+ return+ }+ for i, arg := range os.Args {+ if arg == "--" {+ rootCmd.SetArgs(os.Args[i+1:])+ break+ }+ }+ if err := Execute(); err != nil {+ t.Fatal(err)+ }+}diff --git a/kernel/cli/cmd/root.go b/kernel/cli/cmd/root.goindex 0118b68476..8e80b60e1a 100644--- a/kernel/cli/cmd/root.go+++ b/kernel/cli/cmd/root.go@@ -34,6 +34,7 @@ import ()var (+ homeDirPath stringworkspacePath stringoutputFormat stringdryRun bool@@ -58,6 +59,9 @@ var rootCmd = &cobra.Command{return nil},PersistentPreRunE: func(cmd *cobra.Command, args []string) error {+ if err := util.SetHomeDir(homeDirPath); err != nil {+ return err+ }// workspace 子命令不需要工作空间校验if cmd.Parent() != nil && cmd.Parent().Name() == "workspace" {return nil@@ -283,6 +287,7 @@ func init() {rootCmd.Short = "SiYuan Kernel v" + util.VerrootCmd.Long = "SiYuan Kernel v" + util.Ver + ". Manage workspace data directly or start the HTTP server."+ rootCmd.PersistentFlags().StringVar(&homeDirPath, "home-dir", "", "base directory for user configuration (defaults to the system user home)")rootCmd.PersistentFlags().StringVarP(&workspacePath, "workspace", "w", "", "workspace path")rootCmd.PersistentFlags().StringVarP(&outputFormat, "format", "f", "table", "output format: table | json")rootCmd.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "dry run mode: validate and print what would happen without making changes")diff --git a/kernel/cli/cmd/serve.go b/kernel/cli/cmd/serve.goindex 7dc7239b0d..644aa628e1 100644--- a/kernel/cli/cmd/serve.go+++ b/kernel/cli/cmd/serve.go@@ -49,6 +49,9 @@ var serveCmd = &cobra.Command{Long: "Start kernel HTTP server. All serving-related options below are passed to the kernel boot.",// 这些 flag 由 cobra 解析(见 init),serve -h 可直接列出全部参数。PersistentPreRunE: func(cmd *cobra.Command, args []string) error {+ if err := util.SetHomeDir(homeDirPath); err != nil {+ return err+ }// serve 绕过 root 的初始化,但 --log-level 需在 BootWithFlags(含 logBootInfo 等启动日志)之前应用,// 否则命令行指定的级别会被丢弃;同时记入 util.CLILogLevel,使随后的 model.InitConf 不再用 conf.json 覆盖。if "" != logLevel {diff --git a/kernel/util/path.go b/kernel/util/path.goindex dcca867701..b0884e02cd 100644--- a/kernel/util/path.go+++ b/kernel/util/path.go@@ -551,19 +551,26 @@ func isSensitivePath(p string) bool {// 家目录下的凭据复制进工作空间后外泄:Git push token、HTTP/API 凭据、Postgres 密码、// K8s/Docker/容器仓库配置、GPG 私钥环、云厂商 CLI 凭据、包管理器 token 等。homeDirs := []string{HomeDir}+ // 自定义配置主目录不能使系统用户主目录中的凭据失去保护。+ if homeDirOverridden && systemHomeDir != "" && systemHomeDir != HomeDir {+ homeDirs = append(homeDirs, systemHomeDir)+ if resolved, err := filepath.EvalSymlinks(systemHomeDir); err == nil && resolved != systemHomeDir {+ homeDirs = append(homeDirs, resolved)+ }+ }homeCheckPaths := []string{toCheckPathLower}- if HomeDir != "" && !gulu.File.IsSubPath(HomeDir, p) {- // 工作空间真实路径获得系统目录豁免后,仍需匹配家目录真实路径下的敏感位置。+ if HomeDir != "" {+ // 主目录自身也可能是别名,工作空间规范路径必须同时匹配其真实目录中的敏感位置。if resolved, err := filepath.EvalSymlinks(HomeDir); err == nil && resolved != HomeDir {homeDirs = append(homeDirs, resolved)}- // 家目录已是真实路径而目标仍使用工作空间别名时,按工作空间根目录映射目标。- // 只映射根目录,保留对尚未创建的导出目标及工作空间内路径的检查。- if inWorkspace && workspaceDir == WorkspaceDir {- if resolved, err := filepath.EvalSymlinks(workspaceDir); err == nil && resolved != workspaceDir {- if rel, err := filepath.Rel(workspaceDir, p); err == nil {- homeCheckPaths = append(homeCheckPaths, strings.ToLower(filepath.Join(resolved, rel)))- }+ }+ // 工作空间别名可能位于自定义主目录中,但指向系统主目录中的敏感位置。+ // 只映射工作空间根目录,保留对尚未创建的目标及工作空间内路径的检查。+ if inWorkspace && workspaceDir == WorkspaceDir {+ if resolved, err := filepath.EvalSymlinks(workspaceDir); err == nil && resolved != workspaceDir {+ if rel, err := filepath.Rel(workspaceDir, p); err == nil {+ homeCheckPaths = append(homeCheckPaths, strings.ToLower(filepath.Join(resolved, rel)))}}}diff --git a/kernel/util/runtime.go b/kernel/util/runtime.goindex b591c4c76d..b3a137d4af 100644--- a/kernel/util/runtime.go+++ b/kernel/util/runtime.go@@ -489,14 +489,19 @@ func isICloudPath(workspaceAbsPath string) bool {}// macOS 端对工作空间放置在 iCloud 路径下做检查 https://github.com/siyuan-note/siyuan/issues/7747- iCloudRoot := filepath.Join(HomeDir, "Library", "Mobile Documents")- if resolvedRoot, matched := matchICloudRoot(HomeDir, iCloudRoot, workspacePath); matched {+ if resolvedRoot, matched := matchSystemICloudRoot(workspacePath); matched {logging.LogWarnf("workspace [%s] is in iCloud path [%s]", workspaceAbsPath, resolvedRoot)return true}return false}+// matchSystemICloudRoot 使用系统用户主目录,避免配置目录覆盖改变真实 iCloud 的检测位置。+func matchSystemICloudRoot(workspacePath string) (resolvedRoot string, matched bool) {+ iCloudRoot := filepath.Join(systemHomeDir, "Library", "Mobile Documents")+ return matchICloudRoot(systemHomeDir, iCloudRoot, workspacePath)+}+func longestExistingPath(path string) string {path = filepath.Clean(path)for {diff --git a/kernel/util/working.go b/kernel/util/working.goindex b4dc4e8128..0f74c438ab 100644--- a/kernel/util/working.go+++ b/kernel/util/working.go@@ -119,6 +119,7 @@ func Boot() {IncBootProgress(3, BootL10n(299, "Booting kernel..."))// 由标准库 flag 解析 os.Args,再走统一的 BootWithFlags。+ homeDirPath := flag.String("home-dir", "", "base directory for user configuration (defaults to the system user home)")workspacePath := flag.String("workspace", "", "dir path of the workspace, default to ~/SiYuan/")wdPath := flag.String("wd", WorkingDir, "working directory of SiYuan")port := flag.String("port", "0", "port of the HTTP server")@@ -132,6 +133,11 @@ func Boot() {safeMode := flag.Bool("safe-mode", false, "boot in safe mode")flag.Parse()+ if err := SetHomeDir(*homeDirPath); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(logging.ExitCodeInitWorkspaceErr)+ }+BootWithFlags(*workspacePath, *wdPath, *port, *readOnly, *accessAuthCode, *lang, *mode, *ssl, *attachUI, *safeMode, *enablePprof)}@@ -247,8 +253,10 @@ func SetBooted() {}var (- HomeDir, _ = gulu.OS.Home()- WorkingDir, _ = os.Getwd()+ systemHomeDir, _ = gulu.OS.Home()+ HomeDir = systemHomeDir+ homeDirOverridden bool+ WorkingDir, _ = os.Getwd()WorkspaceDir string // 工作空间目录路径WorkspaceName string // 工作空间名称@@ -274,6 +282,35 @@ var (UIProcessIDs = sync.Map{} // UI 进程 ID)+// SetHomeDir 设置用户配置基路径,配置仍保存在其 .config/siyuan 子目录中。+// 空参数保留默认目录;显式路径必须能创建配置目录,失败时不回退到系统用户主目录。+func SetHomeDir(homeDir string) error {+ if homeDir == "" {+ return nil+ }+ absPath, err := filepath.Abs(homeDir)+ if err != nil {+ return fmt.Errorf("resolve --home-dir [%s] failed: %w", homeDir, err)+ }+ if err = os.MkdirAll(filepath.Join(absPath, ".config", "siyuan"), 0755); err != nil {+ return fmt.Errorf("initialize --home-dir [%s] failed: %w", absPath, err)+ }+ HomeDir = absPath+ homeDirOverridden = true+ return nil+}++// defaultWorkspacePath 保留各平台默认布局,显式配置主目录时不再使用 Windows USERPROFILE。+func defaultWorkspacePath(homeDir, goos, userProfile string, homeDirOverridden bool) string {+ if goos == "windows" && !homeDirOverridden && userProfile != "" {+ return filepath.Join(userProfile, "SiYuan")+ }+ if goos == "darwin" {+ return filepath.Join(homeDir, "Library", "Application Support", "SiYuan")+ }+ return filepath.Join(homeDir, "SiYuan")+}+// MaxUIProcessCount UI 进程注册表条目数上限。const MaxUIProcessCount = 64@@ -298,16 +335,7 @@ func initWorkspaceDir(workspaceArg string) {}}- defaultWorkspaceDir := filepath.Join(HomeDir, "SiYuan")- if gulu.OS.IsWindows() {- // 改进 Windows 端默认工作空间路径 https://github.com/siyuan-note/siyuan/issues/5622- if userProfile := os.Getenv("USERPROFILE"); "" != userProfile {- defaultWorkspaceDir = filepath.Join(userProfile, "SiYuan")- }- } else if gulu.OS.IsDarwin() {- // Change the initial workspace path to ~/Library/Application Support/SiYuan on macOS https://github.com/siyuan-note/siyuan/issues/17095- defaultWorkspaceDir = filepath.Join(HomeDir, "Library", "Application Support", "SiYuan")- }+ defaultWorkspaceDir := defaultWorkspacePath(HomeDir, runtime.GOOS, os.Getenv("USERPROFILE"), homeDirOverridden)var workspacePaths []stringif !gulu.File.IsExist(workspaceConf) {diff --git a/kernel/util/working_home_test.go b/kernel/util/working_home_test.gonew file mode 100644index 0000000000..56e1c22f62--- /dev/null+++ b/kernel/util/working_home_test.go@@ -0,0 +1,287 @@+// SiYuan - From thought to insight, with agents+// 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.++package util++import (+ "flag"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+)++func TestSetHomeDir(t *testing.T) {+ originalHome, originalOverride := HomeDir, homeDirOverridden+ t.Cleanup(func() { HomeDir, homeDirOverridden = originalHome, originalOverride })+ if err := SetHomeDir(""); err != nil || HomeDir != originalHome || homeDirOverridden != originalOverride {+ t.Fatalf("empty home directory changed the default: home=%q, err=%v", HomeDir, err)+ }++ base := t.TempDir()+ cwd, err := os.Getwd()+ if err != nil {+ t.Fatal(err)+ }+ relative, err := filepath.Rel(cwd, filepath.Join(base, "relative-home"))+ if err != nil {+ t.Fatal(err)+ }+ for _, path := range []string{filepath.Join(base, "absolute-home"), relative} {+ if err = SetHomeDir(path); err != nil {+ t.Fatalf("SetHomeDir(%q): %v", path, err)+ }+ want, _ := filepath.Abs(path)+ if HomeDir != want || !homeDirOverridden {+ t.Fatalf("home=%q, overridden=%v, want %q", HomeDir, homeDirOverridden, want)+ }+ if stat, err := os.Stat(filepath.Join(HomeDir, ".config", "siyuan")); err != nil || !stat.IsDir() {+ t.Fatalf("configuration directory was not created: %v", err)+ }+ }+}++func TestSetHomeDirRejectsInvalidPaths(t *testing.T) {+ originalHome, originalOverride := HomeDir, homeDirOverridden+ t.Cleanup(func() { HomeDir, homeDirOverridden = originalHome, originalOverride })+ base := t.TempDir()+ file := filepath.Join(base, "file")+ if err := os.WriteFile(file, []byte("unchanged"), 0600); err != nil {+ t.Fatal(err)+ }+ for _, path := range []string{file, filepath.Join(file, "child"), "invalid\x00path"} {+ if err := SetHomeDir(path); err == nil {+ t.Fatalf("SetHomeDir(%q) accepted an invalid directory", path)+ }+ if HomeDir != originalHome || homeDirOverridden != originalOverride {+ t.Fatal("invalid directory changed the active home")+ }+ }+ data, err := os.ReadFile(file)+ if err != nil || string(data) != "unchanged" {+ t.Fatalf("existing file changed: %q, %v", data, err)+ }+}++func TestSetHomeDirRejectsReadOnlyDirectory(t *testing.T) {+ if runtime.GOOS == "windows" || os.Geteuid() == 0 {+ t.Skip("permission-bit check requires a non-root Unix user")+ }+ originalHome, originalOverride := HomeDir, homeDirOverridden+ t.Cleanup(func() { HomeDir, homeDirOverridden = originalHome, originalOverride })+ path := t.TempDir()+ if err := os.Chmod(path, 0500); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.Chmod(path, 0700) })+ if err := SetHomeDir(path); err == nil {+ t.Fatal("read-only home directory should fail")+ }+ if HomeDir != originalHome {+ t.Fatal("failed initialization changed the active home")+ }+}++func TestDefaultWorkspacePath(t *testing.T) {+ for _, test := range []struct {+ name, goos, profile string+ override bool+ want string+ }{+ {"linux default", "linux", "profile", false, filepath.Join("home", "SiYuan")},+ {"linux override", "linux", "profile", true, filepath.Join("home", "SiYuan")},+ {"windows default", "windows", "profile", false, filepath.Join("profile", "SiYuan")},+ {"windows no profile", "windows", "", false, filepath.Join("home", "SiYuan")},+ {"windows override", "windows", "profile", true, filepath.Join("home", "SiYuan")},+ {"mac default", "darwin", "profile", false, filepath.Join("home", "Library", "Application Support", "SiYuan")},+ {"mac override", "darwin", "profile", true, filepath.Join("home", "Library", "Application Support", "SiYuan")},+ } {+ t.Run(test.name, func(t *testing.T) {+ if got := defaultWorkspacePath("home", test.goos, test.profile, test.override); got != test.want {+ t.Fatalf("default workspace=%q, want %q", got, test.want)+ }+ })+ }+}++func TestBootHomeDir(t *testing.T) {+ base := t.TempDir()+ oldHome, home := filepath.Join(base, "system-home"), filepath.Join(base, "configured-home")+ workspace, wd := filepath.Join(base, "workspace"), filepath.Join(base, "resources")+ for _, dir := range []string{oldHome, workspace, wd} {+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ }+ if runtime.GOOS != "windows" {+ if err := os.Chmod(oldHome, 0500); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.Chmod(oldHome, 0700) })+ }+ command := exec.Command(os.Args[0], "-test.run=^TestBootHomeDirProcess$", "--",+ "--home-dir="+home, "--workspace="+workspace, "--wd="+wd)+ command.Env = append(os.Environ(), "SIYUAN_TEST_BOOT_HOME="+oldHome)+ output, err := command.CombinedOutput()+ if err != nil {+ t.Fatalf("Boot() failed: %v\n%s", err, output)+ }+ for _, expected := range []string{"HOME_DIR=" + home, "WORKSPACE=" + workspace, "WD=" + wd} {+ if !strings.Contains(string(output), expected) {+ t.Fatalf("missing %q in Boot() output:\n%s", expected, output)+ }+ }+ registry := filepath.Join(home, ".config", "siyuan", "workspace.json")+ if _, err = os.Stat(registry); err != nil {+ t.Fatalf("workspace registry was not written under the configured home: %v", err)+ }+ if entries, err := os.ReadDir(oldHome); err != nil || len(entries) != 0 {+ t.Fatalf("system home was accessed for writes: entries=%v, err=%v", entries, err)+ }+}++// TestBootHomeDirProcess 只在测试子进程中初始化路径,不启动 HTTP 服务或数据库。+func TestBootHomeDirProcess(t *testing.T) {+ oldHome := os.Getenv("SIYUAN_TEST_BOOT_HOME")+ if oldHome == "" {+ return+ }+ HomeDir, systemHomeDir = oldHome, oldHome+ for i, arg := range os.Args {+ if arg == "--" {+ os.Args = append([]string{os.Args[0]}, os.Args[i+1:]...)+ break+ }+ }+ flag.CommandLine = flag.NewFlagSet("home-dir-test", flag.ExitOnError)+ Boot()+ defer UnlockWorkspace()+ fmt.Printf("HOME_DIR=%s\nWORKSPACE=%s\nWD=%s\n", HomeDir, WorkspaceDir, WorkingDir)+}++func TestIsSensitivePathWithHomeDirOverride(t *testing.T) {+ originalHome, originalSystem, originalWorkspace := HomeDir, systemHomeDir, WorkspaceDir+ originalOverride := homeDirOverridden+ t.Cleanup(func() {+ HomeDir, systemHomeDir, WorkspaceDir = originalHome, originalSystem, originalWorkspace+ homeDirOverridden = originalOverride+ })+ // 使用虚构路径验证匹配,不读取系统或用户凭据。+ systemHomeDir = filepath.Join(string(filepath.Separator), "home", "system-user")+ HomeDir = filepath.Join(string(filepath.Separator), "home", "configured-user")+ homeDirOverridden = true+ WorkspaceDir = filepath.Join(HomeDir, "SiYuan")+ for _, home := range []string{systemHomeDir, HomeDir} {+ for _, rel := range []string{filepath.Join(".ssh", "config"), filepath.Join(".config", "siyuan", "cookie.key"), ".netrc", ".npmrc"} {+ if path := filepath.Join(home, rel); !IsSensitivePath(path) {+ t.Errorf("credential path is no longer protected: %s", path)+ }+ }+ }+ if path := filepath.Join(WorkspaceDir, "data", "assets", "image.png"); IsSensitivePath(path) {+ t.Errorf("ordinary workspace asset should remain accessible: %s", path)+ }+}++func TestIsSensitivePathHomeDirOverrideWorkspaceAlias(t *testing.T) {+ originalHome, originalSystem, originalWorkspace := HomeDir, systemHomeDir, WorkspaceDir+ originalOverride := homeDirOverridden+ t.Cleanup(func() {+ HomeDir, systemHomeDir, WorkspaceDir = originalHome, originalSystem, originalWorkspace+ homeDirOverridden = originalOverride+ })+ systemHomeDir, HomeDir = t.TempDir(), t.TempDir()+ homeDirOverridden = true+ for _, test := range []struct {+ name, relative string+ sensitive bool+ }{+ {"system config", filepath.Join(".config", "SiYuan"), true},+ {"system ssh", filepath.Join(".ssh", "example"), true},+ {"ordinary workspace", filepath.Join("notebooks", "SiYuan"), false},+ } {+ t.Run(test.name, func(t *testing.T) {+ realWorkspace := filepath.Join(systemHomeDir, test.relative)+ if err := os.MkdirAll(realWorkspace, 0755); err != nil {+ t.Fatal(err)+ }+ WorkspaceDir = filepath.Join(HomeDir, test.name)+ if err := os.Symlink(realWorkspace, WorkspaceDir); err != nil {+ t.Skipf("create workspace symlink: %v", err)+ }+ // 只构造无敏感内容的临时路径,同时覆盖尚未创建的目标。+ for _, root := range []string{WorkspaceDir, realWorkspace} {+ path := filepath.Join(root, "example.txt")+ if got := IsSensitivePath(path); got != test.sensitive {+ t.Errorf("IsSensitivePath(%q)=%v, want %v", path, got, test.sensitive)+ }+ }+ })+ }+}++func TestMatchSystemICloudRootWithHomeDirOverride(t *testing.T) {+ originalHome, originalSystem, originalOverride := HomeDir, systemHomeDir, homeDirOverridden+ t.Cleanup(func() {+ HomeDir, systemHomeDir, homeDirOverridden = originalHome, originalSystem, originalOverride+ })+ systemHomeDir = t.TempDir()+ configuredHome := t.TempDir()+ for _, home := range []string{systemHomeDir, configuredHome} {+ if err := os.MkdirAll(filepath.Join(home, "Library", "Mobile Documents"), 0755); err != nil {+ t.Fatal(err)+ }+ }+ if err := SetHomeDir(configuredHome); err != nil {+ t.Fatal(err)+ }+ for _, test := range []struct {+ home string+ want bool+ }{+ {systemHomeDir, true},+ {configuredHome, false},+ } {+ workspace := filepath.Join(test.home, "Library", "Mobile Documents", "SiYuan")+ if _, matched := matchSystemICloudRoot(workspace); matched != test.want {+ t.Errorf("iCloud detection for %q=%v, want %v", workspace, matched, test.want)+ }+ }+}++func TestIsSensitivePathHomeDirOverrideHomeAlias(t *testing.T) {+ originalHome, originalSystem, originalWorkspace := HomeDir, systemHomeDir, WorkspaceDir+ originalOverride := homeDirOverridden+ t.Cleanup(func() {+ HomeDir, systemHomeDir, WorkspaceDir = originalHome, originalSystem, originalWorkspace+ homeDirOverridden = originalOverride+ })+ realHome := t.TempDir()+ realWorkspace := filepath.Join(realHome, ".config", "SiYuan")+ if err := os.MkdirAll(realWorkspace, 0755); err != nil {+ t.Fatal(err)+ }+ HomeDir = filepath.Join(t.TempDir(), "profile-link")+ if err := os.Symlink(realHome, HomeDir); err != nil {+ t.Skipf("create profile symlink: %v", err)+ }+ if err := os.Symlink(realWorkspace, filepath.Join(realHome, "workspace")); err != nil {+ t.Skipf("create workspace symlink: %v", err)+ }+ systemHomeDir = t.TempDir()+ homeDirOverridden = true+ WorkspaceDir = filepath.Join(HomeDir, "workspace")+ for _, root := range []string{WorkspaceDir, filepath.Join(realHome, "workspace"), realWorkspace} {+ if path := filepath.Join(root, "example.txt"); !IsSensitivePath(path) {+ t.Errorf("configured home credential alias is no longer protected: %s", path)+ }+ }+}