Skip to content

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

:bug: Preserve settings state and repair alpha test regressions

Daniel28097f702dc7
diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.ts
index c68e809abb..30be8a8b04 100644
--- a/app/src/config/entryVisibility/mobileUi.test.ts
+++ b/app/src/config/entryVisibility/mobileUi.test.ts
@@ -309,7 +309,7 @@ test("mobile entry settings preserve preferences and support touch sorting witho
}, async () => {
const modules = ["config/entryVisibility/ui", "config/entryVisibility/catalog", "config/entryVisibility/order",
"config/entryVisibility/profile", "config/entryVisibility/dockOrder", "config/entryVisibility/touchOrder",
- "protyle/toolbar/defaults", "mobile/util/toolbarActions", "protyle/wysiwyg/codeBlockUtil",
+ "protyle/toolbar/defaults", "mobile/util/toolbarActions", "protyle/wysiwyg/codeBlockUtil", "protyle/gutter/turnIntoMenu",
"plugin/dockKey", "plugin/topBarKey", "util/escape"];
const sources = Object.fromEntries(modules.map(id => [id, transpileModule(
readFileSync(path.resolve(process.cwd(), "src", id + ".ts"), "utf8") +
diff --git a/app/src/config/setting/builder.ts b/app/src/config/setting/builder.ts
index 4f37ae31bc..72a86b69bb 100644
--- a/app/src/config/setting/builder.ts
+++ b/app/src/config/setting/builder.ts
@@ -40,7 +40,7 @@ interface ItemsSettingTabOptions<TId extends string = string> extends SettingTab
interface PanelSettingTabOptions<TId extends string = string> extends SettingTabShell<TId> {
searchStrings: () => string[];
- mount: (root: HTMLElement, keywords?: string, app?: App) => void | Promise<void>;
+ mount: (root: HTMLElement, keywords?: string, app?: App, rebuild?: boolean) => void | Promise<void>;
}
type ControlSpecBase = {
@@ -512,10 +512,9 @@ export class SettingBuilder {
let tabSearchIndex: readonly string[] | undefined;
return {
...shell,
- // panel 型 Tab 不支持 rebuild(无注册项可清),忽略该参数以对齐 SettingTab.mount 签名
- mount: async (root, {keywords} = {}, app, _rebuild) => {
- void _rebuild;
- await mount(root, keywords, app);
+ // 面板自行处理配置刷新,保留搜索、展开等交互状态。
+ mount: async (root, {keywords} = {}, app, rebuild) => {
+ await mount(root, keywords, app, rebuild);
},
scanSearch: (keywords) => {
if (tabSearchTitle === undefined) {
diff --git a/app/src/config/tabs/appTab.test.ts b/app/src/config/tabs/appTab.test.ts
index 0ee47f58fd..f3558a8324 100644
--- a/app/src/config/tabs/appTab.test.ts
+++ b/app/src/config/tabs/appTab.test.ts
@@ -12,7 +12,7 @@ type Invoke = (channel: string, data: {cmd: string; enabled?: boolean}) => Promi
type Slot = {key: string; html: () => string; afterMount: (root: unknown) => Promise<void>};
const getAccessibilitySlot = (browser: boolean, mobile: boolean, invoke?: Invoke, slotKey = "accessibilitySupport",
- selects: string[] = []): Slot | undefined => {
+ switches: string[] = []): Slot | undefined => {
const source = readFileSync(resolve(process.cwd(), "src/config/tabs/appTab.ts"), "utf8");
const processed = parse(source, {BROWSER: browser, MOBILE: mobile}, false, true);
const code = transpileModule(processed, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;
@@ -44,8 +44,8 @@ const getAccessibilitySlot = (browser: boolean, mobile: boolean, invoke?: Invoke
get: (_, method) => (value: Slot) => {
if (method === "slot") {
slots.push(value);
- } else if (method === "select") {
- selects.push(String(value));
+ } else if (method === "switch") {
+ switches.push(String(value));
}
},
});
@@ -61,9 +61,9 @@ test("workspace storage is available in desktop, browser and mobile without loca
test("settings window mode is configurable only in the Electron desktop client", () => {
for (const [browser, mobile] of [[false, false], [true, false], [true, true], [false, true]]) {
- const selects: string[] = [];
- getAccessibilitySlot(browser, mobile, undefined, "unused", selects);
- assert.equal(selects.includes("settingsWindowMode"), !browser && !mobile);
+ const switches: string[] = [];
+ getAccessibilitySlot(browser, mobile, undefined, "unused", switches);
+ assert.equal(switches.includes("settingsWindowMode"), !browser && !mobile);
}
});
diff --git a/app/src/config/tabs/keymapUi.test.ts b/app/src/config/tabs/keymapUi.test.ts
new file mode 100644
index 0000000000..5b3e938d64
--- /dev/null
+++ b/app/src/config/tabs/keymapUi.test.ts
@@ -0,0 +1,80 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+test("panel mounts forward refresh intent without changing search and navigation arguments", async () => {
+ const source = createSourceFile("builder.ts", readFileSync("src/config/setting/builder.ts", "utf8"),
+ ScriptTarget.ES2021, true);
+ const builder = source.statements.find(statement => isClassDeclaration(statement) && statement.name.text === "SettingBuilder");
+ assert.ok(isClassDeclaration(builder));
+ const method = builder.members.find(member => isMethodDeclaration(member) && member.name.getText(source) === "panel");
+ assert.ok(method);
+ const code = transpileModule(`export class Builder {${method.getText(source)}}`, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const calls: unknown[][] = [];
+ const exports = {} as {Builder: new () => {panel: (options: unknown) => {
+ mount: (root: unknown, search?: {keywords: string}, app?: unknown, rebuild?: boolean) => Promise<void>;
+ }}};
+ runInNewContext(code, {exports});
+ const panel = new exports.Builder().panel({mount: (...args: unknown[]) => { calls.push(args); }});
+ const root = {};
+ const app = {};
+ await panel.mount(root, {keywords: "shortcut"}, app, true);
+ await panel.mount(root);
+ assert.deepEqual(calls, [[root, "shortcut", app, true], [root, undefined, undefined, undefined]]);
+});
+
+test("keymap refresh retains local search and untouched controls while synchronizing changed bindings", async () => {
+ const source = createSourceFile("keymapUi.ts", readFileSync("src/config/tabs/keymapUi.ts", "utf8"),
+ ScriptTarget.ES2021, true);
+ const declaration = source.statements.find(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(source) === "mountKeymapTab"));
+ assert.ok(declaration);
+ const code = transpileModule(declaration.getText(source), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const unchanged = {dataset: {key: "general|first", keys: '["F9"]'}, controls: {}};
+ const changed = {dataset: {key: "general|second", keys: '["F10"]'}, controls: {}};
+ const controls = unchanged.controls;
+ const search = {value: "Go to tab #5"};
+ const hotkey = {value: "F9", dataset: {keymap: "F9"}};
+ const list = {dataset: {keymapFilter: "customized"}};
+ const root = {
+ innerHTML: "existing panel",
+ querySelectorAll: () => [unchanged, changed],
+ querySelector: (selector: string) => selector === "#keymapInput" ? search :
+ selector === "#searchByKey" ? hotkey : list,
+ };
+ let refreshed = 0;
+ let resets = 0;
+ const exports = {} as {mountKeymapTab: (root: unknown, keywords: undefined, app: undefined, rebuild: boolean) => Promise<void>};
+ runInNewContext(code, {exports, Constants: {ZWSP: "|"},
+ window: {siyuan: {config: {keymap: {first: ["F9"], second: ["F11"]}}}},
+ getKeymapItem: (config: Record<string, string[]>, path: string[]) => config[path[1]],
+ getKeymapBindings: (keys: string[]) => keys,
+ renderRowBindings: (row: typeof unchanged, keys: string[]) => {
+ row.dataset.keys = JSON.stringify(keys);
+ row.controls = {};
+ },
+ refreshKeymapBindings: () => { refreshed++; },
+ resetKeymapList: () => { resets++; },
+ });
+ for (let i = 0; i < 2; i++) {
+ await exports.mountKeymapTab(root, undefined, undefined, true);
+ assert.equal(search.value, "Go to tab #5");
+ assert.equal(hotkey.value, "F9");
+ assert.equal(hotkey.dataset.keymap, "F9");
+ assert.equal(list.dataset.keymapFilter, "customized");
+ assert.equal(unchanged.controls, controls);
+ assert.equal(changed.dataset.keys, '["F11"]');
+ }
+ assert.equal(refreshed, 2);
+ assert.equal(resets, 0);
+ await exports.mountKeymapTab(root, undefined, undefined, false);
+ assert.equal(search.value, "");
+ assert.equal(hotkey.value, "");
+ assert.equal(resets, 1);
+});
diff --git a/app/src/config/tabs/keymapUi.ts b/app/src/config/tabs/keymapUi.ts
index 9b590ec804..3e5bb4f1eb 100644
--- a/app/src/config/tabs/keymapUi.ts
+++ b/app/src/config/tabs/keymapUi.ts
@@ -19,6 +19,7 @@ import {genKeymapRowHtml, getRowBindings, renderRowBindings} from "./keymapRow";
import {escapeHtml} from "../../util/escape";
import {Menu} from "../../plugin/Menu";
import {refreshSettingConfig} from "../setting/sync";
+import type {App} from "../../index";
const keymapToolbarSearchStrings = (): string[] => [
window.siyuan.languages.keymapTip,
@@ -84,7 +85,17 @@ const bindKeymapToolbar = (root: HTMLElement) => {
};
/** 快捷键 Tab 挂载(面板页,不走注册表渲染) */
-export const mountKeymapTab = async (root: HTMLElement, keywords?: string) => {
+export const mountKeymapTab = async (root: HTMLElement, keywords?: string, _app?: App, rebuild = false) => {
+ if (rebuild && root.innerHTML !== "") {
+ root.querySelectorAll<HTMLElement>(".config-keymap__row").forEach(row => {
+ const keys = getKeymapBindings(getKeymapItem(window.siyuan.config.keymap, row.dataset.key.split(Constants.ZWSP)));
+ if (JSON.stringify(keys) !== row.dataset.keys) {
+ renderRowBindings(row, keys);
+ }
+ });
+ refreshKeymapBindings(root);
+ return;
+ }
if (root.innerHTML === "") {
root.innerHTML = genKeymapTabHtml();
bindKeymapToolbar(root);
diff --git a/app/src/menus/layouts.test.ts b/app/src/menus/layouts.test.ts
index 91ecad6d73..8b5ae02cfc 100644
--- a/app/src/menus/layouts.test.ts
+++ b/app/src/menus/layouts.test.ts
@@ -40,6 +40,7 @@ const fixture = (geometryAvailable = true) => {
getAllLayout: () => ({current: true}),
suspendLayoutSaving: () => util.suspendLayoutSaving(),
isWindow: () => false,
+ getSettingsWindowHost: (): undefined => undefined,
getAllEditor: (): unknown[] => [],
withFetchTimeout: async (callback: () => Promise<void>) => callback(),
captureWindowGeometry: async () => geometryAvailable ? geometry : undefined,
diff --git a/app/src/protyle/wysiwyg/blockInsertion.test.ts b/app/src/protyle/wysiwyg/blockInsertion.test.ts
index 5db4e92580..9c33e43cdf 100644
--- a/app/src/protyle/wysiwyg/blockInsertion.test.ts
+++ b/app/src/protyle/wysiwyg/blockInsertion.test.ts
@@ -20,7 +20,7 @@ class TestElement {
return this.selected;
}
- querySelector() {
+ querySelector(): null {
return null;
}
}
diff --git a/app/tests/backlinkSort.test.js b/app/tests/backlinkSort.test.js
index ada31f775a..c0da877c1e 100644
--- a/app/tests/backlinkSort.test.js
+++ b/app/tests/backlinkSort.test.js
@@ -58,8 +58,9 @@ test("anchor sorting is independent, persisted, and refreshes only backlink cont
assert.equal(state.editor.backlinkBlockSort, 1);
assert.equal(state.editor.backlinkSort, 3);
assert.equal(state.editor.backmentionSort, 2);
- assert.equal(state.requests[0].path, "/api/setting/setEditor");
- assert.equal(state.requests[0].data.backlinkBlockSort, 1);
+ assert.equal(state.requests[0].path, "/api/setting/patch");
+ assert.deepEqual(JSON.parse(JSON.stringify(state.requests[0].data)),
+ {editor: {backlinkBlockSort: 1, backlinkGlobalSort: 0}});
assert.equal(state.panel.contextRequestVersions[0], 1);
assert.equal(state.panel.contextRequestVersions[1], 0);
assert.equal(state.folded.contextDirty, true);
@@ -91,7 +92,8 @@ test("global sorting selects a flat mode and document sorting restores grouping"
const header = state.menuItems.findIndex(item => item.label === "backlinkGlobalSort");
state.menuItems[header + 1].click();
assert.equal(state.editor.backlinkGlobalSort, 1);
- assert.equal(state.requests[0].data.backlinkGlobalSort, 1);
+ assert.equal(state.requests[0].path, "/api/setting/patch");
+ assert.deepEqual(JSON.parse(JSON.stringify(state.requests[0].data)), {editor: {backlinkGlobalSort: 1}});
state.panel.showSortMenu("sort", "3");
assert.equal(state.menuItems.filter(item => item.checked).length, 1);
assert.equal(state.menuItems[header + 1].checked, true);
diff --git a/app/tests/mobileEditingToolbar.test.js b/app/tests/mobileEditingToolbar.test.js
index b4d72df822..1d26e8d1ac 100644
--- a/app/tests/mobileEditingToolbar.test.js
+++ b/app/tests/mobileEditingToolbar.test.js
@@ -99,7 +99,7 @@ const runCases = async (sources, platform) => {
wysiwyg: {element: root}, preview: {element: preview},
options: {toolbar: load("protyle/toolbar/defaults").getDefaultToolbar(true)},
toolbar: {isMultiSelectMode: () => false, getCurrentToolbarType: () => [], setInlineMark: () => editable.focus()},
- gutter: {}, undo: {undo: () => undoCalls++}, hint: {fill: value => inserts.push(value)}};
+ gutter: {}, undo: {undo: () => undoCalls++}, hint: {fillCommand: value => inserts.push(value)}};
const keyboard = load("mobile/util/keyboardToolbar");
keyboard.initKeyboardToolbar();
load("mobile/inputBindings");
diff --git a/app/tests/newRefDocAtPath.test.js b/app/tests/newRefDocAtPath.test.js
index 5c0b977bec..c46aba95b7 100644
--- a/app/tests/newRefDocAtPath.test.js
+++ b/app/tests/newRefDocAtPath.test.js
@@ -218,6 +218,7 @@ const databaseFixture = (view = "table", isDetached = true) => {
const operations = [];
const animations = [];
Object.assign(f.deps, load("protyle/render/av/binding", f.deps, f.window, f.Lute),
+ load("protyle/render/av/bindCreatedDocument", f.deps, f.window, f.Lute),
load("protyle/render/av/viewType", f.deps, f.window, f.Lute), {
hasClosestByClassName: (node, name) => {
if (name === "av__cell") {
@@ -238,7 +239,7 @@ const databaseFixture = (view = "table", isDetached = true) => {
});
};
-test("database creation binds only after success and preserves item identity and undo", () => {
+test("database creation binds only after success and preserves item identity and undo", async () => {
for (const view of ["table", "list", "gallery", "kanban"]) {
for (const isDetached of [false, true]) {
const f = databaseFixture(view, isDetached);
@@ -248,6 +249,7 @@ test("database creation binds only after success and preserves item identity and
assert.equal(f.animations.length, 0);
assert.equal(f.requests[0].data.path, "/chosen-parent/20260927120000-newdoc1.sy");
f.requests[0].cb({code: 0});
+ await Promise.resolve();
assert.equal(f.operations.length, 1);
const {doOperations, undoOperations} = f.operations[0];
assert.equal(doOperations[0].previousID, "original-item");
@@ -274,7 +276,7 @@ test("canceling database location selection leaves the original binding and disp
assert.equal(f.focused.length, 1);
});
-test("database context changes before confirmation or after creation starts cannot replace another binding", () => {
+test("database context changes before confirmation or after creation starts cannot replace another binding", async () => {
const changes = [
f => { f.cell.isConnected = false; },
f => { f.block.isConnected = false; },
@@ -296,6 +298,7 @@ test("database context changes before confirmation or after creation starts cann
change(f);
if (afterCreate) {
f.requests[0].cb({code: 0});
+ await Promise.resolve();
} else {
f.picker.cb(["/"], ["other"]);
assert.equal(f.requests.length, 0);
diff --git a/docs/LIST-MINDMAP.md b/docs/LIST-MINDMAP.md
index 932522f928..f19cbdc2e7 100644
--- a/docs/LIST-MINDMAP.md
+++ b/docs/LIST-MINDMAP.md
@@ -1,6 +1,6 @@
# 列表脑图
-列表脑图是列表块的另一种视图,入口位于列表块菜单 - 切换为脑图视图。列表项菜单不提供这个入口。斜杠菜单和移动端新建脑图直接生成列表脑图,保留原有菜单配置标识。
+列表脑图使用独立的 `NodeMindmap` 和 `NodeMindmapItem` 块类型,支持与列表相互转换,入口位于列表块菜单 - 切换为脑图视图。列表项菜单不提供这个入口。斜杠菜单和移动端新建脑图直接生成脑图块,保留原有菜单配置标识。
打开可编辑文档时,编辑器在首次内容渲染前请求内核迁移旧 `mindmap` 代码块。内核在事务串行区读取整份文档,包括折叠和分页未加载的内容;先保存可恢复的文档历史,再通过一次文档事务转换,保留原块 ID、属性、列表层级、正文和任务状态,并为新增子块生成新 ID。转换支持统一撤销和重做;同一编辑器的当前文档只尝试一次,撤销后再次打开文档才会重新迁移。已转换的块不会重复转换,后续同步或导入的旧内容在下次打开时处理。
@@ -35,9 +35,11 @@
## 数据与兼容性
-正文仍存放在原列表和原列表项中,搜索、块引用和反链继续使用原块 ID。单个顶层列表项直接作为根节点;多个顶层项使用可自定义标题的虚拟中心节点,它不新增实际块,标题存放在脑图属性的可选 `rootTitle` 字段中。
+列表与脑图转换保留已有容器、节点和正文块的 ID,搜索、块引用和反链继续使用原块 ID。单个顶层项直接作为根节点;多个顶层项使用可自定义标题的虚拟中心节点,脑图显示时不新增实际块,标题存放在脑图属性的可选 `rootTitle` 字段中。
-列表块使用 `custom-sy-list-mindmap="1"` 启用脑图视图。`custom-sy-list-mindmap-data` 保存版本为 `1` 的节点样式和关系线配置。关闭脑图视图保留该配置;折叠使用列表项的已有 `fold` 属性。未知版本或损坏的配置不会被自动覆盖,原列表仍可查看。
+带有非空标题的虚拟根转换为列表时,标题实体化为真实父项,新增父项、标题段落和子列表三个块,原顶层项移入该子列表。所有已有块 ID 和正文保留,原顶层项的父子关系相应调整;虚拟根样式、关系线端点和概要父节点迁移至新父项,移除 `rootTitle`。再次往返不会重复新增父项,撤销恢复转换前结构。无标题的虚拟根不新增这些块。
+
+旧列表上的 `custom-sy-list-mindmap="1"` 标记仍受兼容处理,新脑图以专用块类型保存。`custom-sy-list-mindmap-data` 保存版本为 `1` 的节点样式和关系线配置。转换为列表保留该配置;折叠沿用节点的 `fold` 属性。未知版本或损坏的配置不会被自动覆盖,原正文仍可查看。
关系线可选的 `route` 字段使用独立的 `version: 1`,`points` 保存不超过 64 个控制点。每个控制点的 `x`、`y` 是相对两个节点中心插值位置的偏移,`t` 是沿路径长度计算的插值比例(0 到 1),坐标偏移的绝对值不超过 1000000。缺少 `route` 表示自动中间路径;双击线段手柄恢复时只删除该字段,保留文字、样式和端点连接点。关系线的可选 `fromAnchor`、`toAnchor` 分别保存起点和终点的手动连接位置,每项包含 `side`(`left`、`right`、`top` 或 `bottom`)和 `ratio`(0 到 1);缺少相应字段表示该端自动选择,元数据版本仍为 `1`,旧配置无需迁移。比例跟随节点尺寸,位置跟随节点布局;“恢复自动接入”只删除这两个字段,不删除 `route`。未知版本及损坏配置保留原值。布局变化时优先重新使用手动路径;若手动路径无法避障,则保留指定连接点并暂时显示自动中间路径;指定连接点也无法使用时,才暂时显示自动连接点。两类回退分别显示明确提示,保存的路径和连接点均保留,恢复可用布局后重新使用;只读交互视图也显示提示,打印可隐藏提示但采用相同的几何规则。拖动期间的外部刷新取消预览,提交前核对关系线快照,避免覆盖较新的配置。
diff --git a/kernel/api/contract_system_test.go b/kernel/api/contract_system_test.go
index 79993f936c..3890c6f22d 100644
--- a/kernel/api/contract_system_test.go
+++ b/kernel/api/contract_system_test.go
@@ -200,6 +200,9 @@ func TestAPIContractSystemRawResponses(t *testing.T) {
}
func TestAPIContractSystemUploadErrors(t *testing.T) {
+ previousConf := model.Conf
+ model.Conf = model.NewAppConf()
+ t.Cleanup(func() { model.Conf = previousConf })
for _, test := range []struct {
route string
handler gin.HandlerFunc
diff --git a/kernel/util/path.go b/kernel/util/path.go
index b0884e02cd..94c538ef3c 100644
--- a/kernel/util/path.go
+++ b/kernel/util/path.go
@@ -446,7 +446,7 @@ func IsPartitionRootPath(path string) bool {
// globalCopyFiles 等接受工作空间外绝对路径的接口的攻击面。工作空间内的路径不解析符号链接,
// 一是因为工作空间内文件(如 assets 中指向外部目录的符号链接)可能合法地指向工作空间外,
// 对其解析后执行系统目录前缀检查会误伤;二是避免在高 QPS 的伺服热路径上引入额外的 stat 开销。
-// 解析失败(如路径不存在)时回退到仅检查原始路径。
+// 目标尚未创建时解析最长已存在的父目录,避免别名下的新文件绕过敏感目录检查。
func IsSensitivePath(p string) bool {
if p == "" {
return false
@@ -458,8 +458,8 @@ func IsSensitivePath(p string) bool {
if gulu.File.IsSubPath(WorkspaceDir, p) {
return false
}
- resolved, err := filepath.EvalSymlinks(p)
- if err == nil && resolved != p {
+ resolved := ResolveLongestExistingParent(p)
+ if resolved != p {
if isSensitivePath(resolved) {
return true
}
diff --git a/kernel/util/path_test.go b/kernel/util/path_test.go
index 06ab9c6097..78f10f801a 100644
--- a/kernel/util/path_test.go
+++ b/kernel/util/path_test.go
@@ -170,6 +170,32 @@ func TestIsSensitivePathWorkspaceFilesNotBlocked(t *testing.T) {
}
}
+func TestIsSensitivePathWorkspaceAssetSymlink(t *testing.T) {
+ originalHome, originalWorkspace := HomeDir, WorkspaceDir
+ HomeDir, WorkspaceDir = t.TempDir(), t.TempDir()
+ t.Cleanup(func() { HomeDir, WorkspaceDir = originalHome, originalWorkspace })
+ target := filepath.Join(HomeDir, ".config", "example")
+ if err := os.MkdirAll(target, 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(target, "existing.txt"), []byte("fixture"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ assets := filepath.Join(WorkspaceDir, "data", "assets")
+ if err := os.MkdirAll(assets, 0755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(assets, "linked")
+ if err := os.Symlink(target, link); err != nil {
+ t.Skipf("create asset symlink: %v", err)
+ }
+ for _, relative := range []string{"existing.txt", filepath.Join("missing", "example.txt")} {
+ if path := filepath.Join(link, relative); IsSensitivePath(path) {
+ t.Errorf("workspace asset symlink should remain allowed: %s", path)
+ }
+ }
+}
+
// TestIsSensitivePathSymlinkWorkspace 验证工作空间父目录为符号链接时的真实路径判定。
func TestIsSensitivePathSymlinkWorkspace(t *testing.T) {
realHome, err := filepath.EvalSymlinks(t.TempDir())
diff --git a/kernel/util/working_home_test.go b/kernel/util/working_home_test.go
index 56e1c22f62..eb69ea91e8 100644
--- a/kernel/util/working_home_test.go
+++ b/kernel/util/working_home_test.go
@@ -279,9 +279,14 @@ func TestIsSensitivePathHomeDirOverrideHomeAlias(t *testing.T) {
systemHomeDir = t.TempDir()
homeDirOverridden = true
WorkspaceDir = filepath.Join(HomeDir, "workspace")
+ if err := os.WriteFile(filepath.Join(realWorkspace, "existing.txt"), []byte("fixture"), 0600); err != nil {
+ t.Fatal(err)
+ }
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)
+ for _, relative := range []string{"existing.txt", "example.txt", filepath.Join("missing", "example.txt")} {
+ if path := filepath.Join(root, relative); !IsSensitivePath(path) {
+ t.Errorf("configured home credential alias is no longer protected: %s", path)
+ }
}
}
}