@dexto/tools-filesystem 1.16.0 → 1.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,311 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var import_vitest = require("vitest");
25
+ var path = __toESM(require("node:path"), 1);
26
+ var fs = __toESM(require("node:fs/promises"), 1);
27
+ var os = __toESM(require("node:os"), 1);
28
+ var import_safe_fs = require("./safe-fs.js");
29
+ var import_filesystem_service = require("./filesystem-service.js");
30
+ var import_path_validator = require("./path-validator.js");
31
+ var import_directory_approval = require("./directory-approval.js");
32
+ const createMockLogger = () => {
33
+ const logger = {
34
+ debug: import_vitest.vi.fn(),
35
+ silly: import_vitest.vi.fn(),
36
+ info: import_vitest.vi.fn(),
37
+ warn: import_vitest.vi.fn(),
38
+ error: import_vitest.vi.fn(),
39
+ trackException: import_vitest.vi.fn(),
40
+ createChild: import_vitest.vi.fn(() => logger),
41
+ createFileOnlyChild: import_vitest.vi.fn(() => logger),
42
+ setLevel: import_vitest.vi.fn(),
43
+ getLevel: import_vitest.vi.fn(() => "debug"),
44
+ getLogFilePath: import_vitest.vi.fn(() => null),
45
+ destroy: import_vitest.vi.fn(async () => void 0)
46
+ };
47
+ return logger;
48
+ };
49
+ const describeSymlinks = process.platform === "win32" ? import_vitest.describe.skip : import_vitest.describe;
50
+ describeSymlinks("symlink containment", () => {
51
+ let root;
52
+ let allowed;
53
+ let outside;
54
+ const config = (allowedPaths = [allowed]) => ({
55
+ allowedPaths,
56
+ blockedPaths: [],
57
+ blockedExtensions: [],
58
+ maxFileSize: 10 * 1024 * 1024,
59
+ workingDirectory: allowed,
60
+ enableBackups: false,
61
+ backupRetentionDays: 7
62
+ });
63
+ const listOutside = async () => (await fs.readdir(outside, { recursive: true })).sort();
64
+ (0, import_vitest.beforeEach)(async () => {
65
+ root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "dexto-safe-fs-")));
66
+ allowed = path.join(root, "allowed");
67
+ outside = path.join(root, "outside");
68
+ await fs.mkdir(allowed);
69
+ await fs.mkdir(outside);
70
+ });
71
+ (0, import_vitest.afterEach)(async () => {
72
+ await fs.rm(root, { recursive: true, force: true });
73
+ });
74
+ (0, import_vitest.describe)("canonicalizePath", () => {
75
+ (0, import_vitest.it)("returns realpath for existing paths", async () => {
76
+ await fs.symlink(outside, path.join(allowed, "link"));
77
+ (0, import_vitest.expect)(await (0, import_safe_fs.canonicalizePath)(path.join(allowed, "link"))).toBe(outside);
78
+ });
79
+ (0, import_vitest.it)("resolves the nearest existing ancestor for missing paths", async () => {
80
+ await fs.symlink(outside, path.join(allowed, "link"));
81
+ (0, import_vitest.expect)(await (0, import_safe_fs.canonicalizePath)(path.join(allowed, "link", "a", "b.txt"))).toBe(
82
+ path.join(outside, "a", "b.txt")
83
+ );
84
+ });
85
+ (0, import_vitest.it)("follows dangling symlinks, including relative ones", async () => {
86
+ await fs.symlink(path.join(outside, "missing.txt"), path.join(allowed, "abs"));
87
+ await fs.symlink("../outside/rel.txt", path.join(allowed, "rel"));
88
+ (0, import_vitest.expect)(await (0, import_safe_fs.canonicalizePath)(path.join(allowed, "abs"))).toBe(
89
+ path.join(outside, "missing.txt")
90
+ );
91
+ (0, import_vitest.expect)(await (0, import_safe_fs.canonicalizePath)(path.join(allowed, "rel"))).toBe(
92
+ path.join(outside, "rel.txt")
93
+ );
94
+ });
95
+ (0, import_vitest.it)("follows chains of dangling symlinks", async () => {
96
+ await fs.symlink(path.join(outside, "end.txt"), path.join(allowed, "b"));
97
+ await fs.symlink(path.join(allowed, "b"), path.join(allowed, "a"));
98
+ (0, import_vitest.expect)(await (0, import_safe_fs.canonicalizePath)(path.join(allowed, "a"))).toBe(
99
+ path.join(outside, "end.txt")
100
+ );
101
+ });
102
+ (0, import_vitest.it)("rejects symlink loops", async () => {
103
+ await fs.symlink(path.join(allowed, "loop-b"), path.join(allowed, "loop-a"));
104
+ await fs.symlink(path.join(allowed, "loop-a"), path.join(allowed, "loop-b"));
105
+ await (0, import_vitest.expect)((0, import_safe_fs.canonicalizePath)(path.join(allowed, "loop-a", "x"))).rejects.toThrow();
106
+ });
107
+ });
108
+ (0, import_vitest.describe)("PathValidator", () => {
109
+ (0, import_vitest.it)("rejects new paths that resolve outside through a directory symlink", async () => {
110
+ await fs.symlink(outside, path.join(allowed, "link"));
111
+ const validator = new import_path_validator.PathValidator(config(), createMockLogger());
112
+ const result = await validator.validatePath("link/new.txt", "write");
113
+ (0, import_vitest.expect)(result.isValid).toBe(false);
114
+ });
115
+ (0, import_vitest.it)("rejects dangling symlinks that point outside", async () => {
116
+ await fs.symlink(path.join(outside, "x.txt"), path.join(allowed, "dangling"));
117
+ const validator = new import_path_validator.PathValidator(config(), createMockLogger());
118
+ (0, import_vitest.expect)((await validator.validatePath("dangling", "write")).isValid).toBe(false);
119
+ (0, import_vitest.expect)(await validator.isPathWithinAllowed("dangling")).toBe(false);
120
+ });
121
+ (0, import_vitest.it)("accepts new files under an allowed root reached through a symlink", async () => {
122
+ const linkedRoot = path.join(root, "linked-root");
123
+ await fs.symlink(allowed, linkedRoot);
124
+ const validator = new import_path_validator.PathValidator(config([linkedRoot]), createMockLogger());
125
+ const result = await validator.validatePath(path.join(linkedRoot, "new.txt"), "write");
126
+ (0, import_vitest.expect)(result.isValid).toBe(true);
127
+ (0, import_vitest.expect)(result.normalizedPath).toBe(path.join(allowed, "new.txt"));
128
+ });
129
+ (0, import_vitest.it)("rejects paths that a blocked path matches only lexically", async () => {
130
+ await fs.mkdir(path.join(allowed, "real-secret"));
131
+ await fs.symlink(path.join(allowed, "real-secret"), path.join(allowed, "secret"));
132
+ const validator = new import_path_validator.PathValidator(
133
+ { ...config(), blockedPaths: [path.join(allowed, "secret")] },
134
+ createMockLogger()
135
+ );
136
+ (0, import_vitest.expect)((await validator.validatePath("secret/new.txt", "write")).isValid).toBe(false);
137
+ });
138
+ });
139
+ (0, import_vitest.describe)("FileSystemService writes", () => {
140
+ (0, import_vitest.it)("does not create files outside through a directory symlink", async () => {
141
+ await fs.symlink(outside, path.join(allowed, "link"));
142
+ const service = new import_filesystem_service.FileSystemService(config(), createMockLogger());
143
+ await (0, import_vitest.expect)(service.writeFile("link/new.txt", "x")).rejects.toThrow();
144
+ await (0, import_vitest.expect)(service.writeFile("link/sub/deep.txt", "x")).rejects.toThrow();
145
+ (0, import_vitest.expect)(await listOutside()).toEqual([]);
146
+ });
147
+ (0, import_vitest.it)("does not create files outside through a dangling symlink", async () => {
148
+ await fs.symlink(path.join(outside, "x.txt"), path.join(allowed, "dangling"));
149
+ const service = new import_filesystem_service.FileSystemService(config(), createMockLogger());
150
+ await (0, import_vitest.expect)(service.writeFile("dangling", "x")).rejects.toThrow();
151
+ (0, import_vitest.expect)(await listOutside()).toEqual([]);
152
+ });
153
+ (0, import_vitest.it)("writes the target of a dangling symlink that stays inside", async () => {
154
+ await fs.mkdir(path.join(allowed, "sub"));
155
+ await fs.symlink(path.join(allowed, "sub", "target.txt"), path.join(allowed, "link"));
156
+ const service = new import_filesystem_service.FileSystemService(config(), createMockLogger());
157
+ const result = await service.writeFile("link", "inside");
158
+ (0, import_vitest.expect)(result.path).toBe(path.join(allowed, "sub", "target.txt"));
159
+ (0, import_vitest.expect)(await fs.readFile(path.join(allowed, "sub", "target.txt"), "utf-8")).toBe(
160
+ "inside"
161
+ );
162
+ });
163
+ (0, import_vitest.it)("does not edit files outside through a symlink", async () => {
164
+ await fs.writeFile(path.join(outside, "f.txt"), "old");
165
+ await fs.symlink(path.join(outside, "f.txt"), path.join(allowed, "f.txt"));
166
+ const service = new import_filesystem_service.FileSystemService(config(), createMockLogger());
167
+ await (0, import_vitest.expect)(
168
+ service.editFile("f.txt", { oldString: "old", newString: "new" })
169
+ ).rejects.toThrow();
170
+ (0, import_vitest.expect)(await fs.readFile(path.join(outside, "f.txt"), "utf-8")).toBe("old");
171
+ });
172
+ (0, import_vitest.it)("still writes and overwrites regular files inside allowed paths", async () => {
173
+ const service = new import_filesystem_service.FileSystemService(config(), createMockLogger());
174
+ await service.writeFile("dir/a.txt", "first");
175
+ await service.writeFile("dir/a.txt", "second");
176
+ (0, import_vitest.expect)(await fs.readFile(path.join(allowed, "dir", "a.txt"), "utf-8")).toBe("second");
177
+ });
178
+ });
179
+ (0, import_vitest.describe)("writeFileNoFollow (path swapped after validation)", () => {
180
+ const insideAllowed = (candidate) => {
181
+ const relative = path.relative(allowed, candidate);
182
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
183
+ };
184
+ (0, import_vitest.it)("refuses when the final component became a symlink", async () => {
185
+ await fs.writeFile(path.join(outside, "victim.txt"), "original");
186
+ const target = path.join(allowed, "file.txt");
187
+ await fs.symlink(path.join(outside, "victim.txt"), target);
188
+ await (0, import_vitest.expect)(
189
+ (0, import_safe_fs.writeFileNoFollow)(target, "clobbered", "utf-8", insideAllowed)
190
+ ).rejects.toThrow();
191
+ (0, import_vitest.expect)(await fs.readFile(path.join(outside, "victim.txt"), "utf-8")).toBe("original");
192
+ });
193
+ (0, import_vitest.it)("refuses and does not truncate when a parent directory became a symlink", async () => {
194
+ await fs.writeFile(path.join(outside, "victim.txt"), "original");
195
+ const target = path.join(allowed, "sub", "victim.txt");
196
+ await fs.symlink(outside, path.join(allowed, "sub"));
197
+ await (0, import_vitest.expect)(
198
+ (0, import_safe_fs.writeFileNoFollow)(target, "clobbered", "utf-8", insideAllowed)
199
+ ).rejects.toThrow(/changed during/);
200
+ (0, import_vitest.expect)(await fs.readFile(path.join(outside, "victim.txt"), "utf-8")).toBe("original");
201
+ });
202
+ (0, import_vitest.it)("truncates existing content on a normal overwrite", async () => {
203
+ const target = path.join(allowed, "f.txt");
204
+ await fs.writeFile(target, "a much longer original");
205
+ await (0, import_safe_fs.writeFileNoFollow)(target, "short", "utf-8", insideAllowed);
206
+ (0, import_vitest.expect)(await fs.readFile(target, "utf-8")).toBe("short");
207
+ });
208
+ (0, import_vitest.it)("removes a file it created when post-open verification fails", async () => {
209
+ const target = path.join(allowed, "new.txt");
210
+ await (0, import_vitest.expect)((0, import_safe_fs.writeFileNoFollow)(target, "x", "utf-8", () => false)).rejects.toThrow(
211
+ /changed during/
212
+ );
213
+ await (0, import_vitest.expect)(fs.lstat(target)).rejects.toThrow();
214
+ });
215
+ (0, import_vitest.it)("does not create directories through a swapped parent", async () => {
216
+ await fs.symlink(outside, path.join(allowed, "sub"));
217
+ await (0, import_vitest.expect)(
218
+ (0, import_safe_fs.writeFileNoFollow)(
219
+ path.join(allowed, "sub", "deeper", "f.txt"),
220
+ "x",
221
+ "utf-8",
222
+ insideAllowed
223
+ )
224
+ ).rejects.toThrow();
225
+ (0, import_vitest.expect)(await listOutside()).toEqual([]);
226
+ });
227
+ });
228
+ (0, import_vitest.describe)("roots and blocked paths behind symlinks", () => {
229
+ (0, import_vitest.it)("blocks a relative blocked path reached through an alias when the root is behind a symlink", async () => {
230
+ const realBase = path.join(root, "real");
231
+ await fs.mkdir(path.join(realBase, "proj", ".git"), { recursive: true });
232
+ await fs.symlink(realBase, path.join(root, "tmp"));
233
+ const lexicalRoot = path.join(root, "tmp", "proj");
234
+ await fs.symlink(
235
+ path.join(realBase, "proj", ".git"),
236
+ path.join(realBase, "proj", "alias")
237
+ );
238
+ const validator = new import_path_validator.PathValidator(
239
+ {
240
+ ...config([lexicalRoot]),
241
+ workingDirectory: lexicalRoot,
242
+ blockedPaths: [".git"]
243
+ },
244
+ createMockLogger()
245
+ );
246
+ (0, import_vitest.expect)((await validator.validatePath(".git/config", "write")).isValid).toBe(false);
247
+ (0, import_vitest.expect)((await validator.validatePath("alias/config", "write")).isValid).toBe(false);
248
+ (0, import_vitest.expect)((await validator.validatePath("alias/pre-commit", "write")).isValid).toBe(false);
249
+ (0, import_vitest.expect)((await validator.validatePath("src/new.ts", "write")).isValid).toBe(true);
250
+ });
251
+ (0, import_vitest.it)("does not widen allowed paths when a symlink is planted at a root later", async () => {
252
+ const futureRoot = path.join(root, "future");
253
+ const validator = new import_path_validator.PathValidator(config([futureRoot]), createMockLogger());
254
+ (0, import_vitest.expect)(
255
+ (await validator.validatePath(path.join(futureRoot, "a.txt"), "write")).isValid
256
+ ).toBe(true);
257
+ await fs.symlink(outside, futureRoot);
258
+ const escaped = await validator.validatePath(path.join(outside, "x.txt"), "write");
259
+ (0, import_vitest.expect)(escaped.isValid).toBe(false);
260
+ const throughRoot = await validator.validatePath(
261
+ path.join(futureRoot, "x.txt"),
262
+ "write"
263
+ );
264
+ (0, import_vitest.expect)(throughRoot.isValid).toBe(false);
265
+ });
266
+ (0, import_vitest.it)("accepts deep new paths (more than 40 levels)", async () => {
267
+ const deep = path.join(...Array.from({ length: 50 }, (_, i) => `d${i}`), "f.txt");
268
+ const validator = new import_path_validator.PathValidator(config(), createMockLogger());
269
+ (0, import_vitest.expect)((await validator.validatePath(deep, "write")).isValid).toBe(true);
270
+ });
271
+ });
272
+ (0, import_vitest.describe)("delete and rename act on links themselves", () => {
273
+ (0, import_vitest.it)("deletes a dangling symlink that points outside without touching the target", async () => {
274
+ await fs.symlink(path.join(outside, "missing.txt"), path.join(allowed, "dangling"));
275
+ const service = new import_filesystem_service.FileSystemService(config(), createMockLogger());
276
+ await service.deletePath("dangling");
277
+ await (0, import_vitest.expect)(fs.lstat(path.join(allowed, "dangling"))).rejects.toThrow();
278
+ });
279
+ (0, import_vitest.it)("deletes a symlink, not the file it points to", async () => {
280
+ await fs.writeFile(path.join(allowed, "target.txt"), "keep");
281
+ await fs.symlink(path.join(allowed, "target.txt"), path.join(allowed, "link"));
282
+ const service = new import_filesystem_service.FileSystemService(config(), createMockLogger());
283
+ await service.deletePath("link");
284
+ (0, import_vitest.expect)(await fs.readFile(path.join(allowed, "target.txt"), "utf-8")).toBe("keep");
285
+ });
286
+ (0, import_vitest.it)("refuses to move a file into a directory symlink that points outside", async () => {
287
+ await fs.writeFile(path.join(allowed, "f.txt"), "data");
288
+ await fs.symlink(outside, path.join(allowed, "link"));
289
+ const service = new import_filesystem_service.FileSystemService(config(), createMockLogger());
290
+ await (0, import_vitest.expect)(service.renamePath("f.txt", "link/f.txt")).rejects.toThrow();
291
+ (0, import_vitest.expect)(await listOutside()).toEqual([]);
292
+ });
293
+ });
294
+ (0, import_vitest.describe)("directory approval", () => {
295
+ (0, import_vitest.it)("matches files under an approved directory reached through a symlink", async () => {
296
+ const linkedDir = path.join(root, "linked-outside");
297
+ await fs.symlink(outside, linkedDir);
298
+ const canonicalDir = await (0, import_safe_fs.canonicalizePath)(linkedDir);
299
+ const approvals = /* @__PURE__ */ new Map([
300
+ [(0, import_directory_approval.createDirectoryApprovalKey)(canonicalDir, "write"), "session"]
301
+ ]);
302
+ const validator = new import_path_validator.PathValidator(config(), createMockLogger());
303
+ validator.setDirectoryApprovalChecker(
304
+ (filePath, operation) => (0, import_directory_approval.isPathApprovedByDirectoryKey)(filePath, approvals, void 0, operation)
305
+ );
306
+ const result = await validator.validatePath(path.join(linkedDir, "new.txt"), "write");
307
+ (0, import_vitest.expect)(result.isValid).toBe(true);
308
+ (0, import_vitest.expect)(result.normalizedPath).toBe(path.join(outside, "new.txt"));
309
+ });
310
+ });
311
+ });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Symlink containment tests for path canonicalization and file writes.
3
+ */
4
+ export {};
5
+ //# sourceMappingURL=safe-fs.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"safe-fs.test.d.ts","sourceRoot":"","sources":["../src/safe-fs.test.ts"],"names":[],"mappings":"AAAA;;GAEG"}
@@ -0,0 +1,288 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
2
+ import * as path from "node:path";
3
+ import * as fs from "node:fs/promises";
4
+ import * as os from "node:os";
5
+ import { canonicalizePath, writeFileNoFollow } from "./safe-fs.js";
6
+ import { FileSystemService } from "./filesystem-service.js";
7
+ import { PathValidator } from "./path-validator.js";
8
+ import { createDirectoryApprovalKey, isPathApprovedByDirectoryKey } from "./directory-approval.js";
9
+ const createMockLogger = () => {
10
+ const logger = {
11
+ debug: vi.fn(),
12
+ silly: vi.fn(),
13
+ info: vi.fn(),
14
+ warn: vi.fn(),
15
+ error: vi.fn(),
16
+ trackException: vi.fn(),
17
+ createChild: vi.fn(() => logger),
18
+ createFileOnlyChild: vi.fn(() => logger),
19
+ setLevel: vi.fn(),
20
+ getLevel: vi.fn(() => "debug"),
21
+ getLogFilePath: vi.fn(() => null),
22
+ destroy: vi.fn(async () => void 0)
23
+ };
24
+ return logger;
25
+ };
26
+ const describeSymlinks = process.platform === "win32" ? describe.skip : describe;
27
+ describeSymlinks("symlink containment", () => {
28
+ let root;
29
+ let allowed;
30
+ let outside;
31
+ const config = (allowedPaths = [allowed]) => ({
32
+ allowedPaths,
33
+ blockedPaths: [],
34
+ blockedExtensions: [],
35
+ maxFileSize: 10 * 1024 * 1024,
36
+ workingDirectory: allowed,
37
+ enableBackups: false,
38
+ backupRetentionDays: 7
39
+ });
40
+ const listOutside = async () => (await fs.readdir(outside, { recursive: true })).sort();
41
+ beforeEach(async () => {
42
+ root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "dexto-safe-fs-")));
43
+ allowed = path.join(root, "allowed");
44
+ outside = path.join(root, "outside");
45
+ await fs.mkdir(allowed);
46
+ await fs.mkdir(outside);
47
+ });
48
+ afterEach(async () => {
49
+ await fs.rm(root, { recursive: true, force: true });
50
+ });
51
+ describe("canonicalizePath", () => {
52
+ it("returns realpath for existing paths", async () => {
53
+ await fs.symlink(outside, path.join(allowed, "link"));
54
+ expect(await canonicalizePath(path.join(allowed, "link"))).toBe(outside);
55
+ });
56
+ it("resolves the nearest existing ancestor for missing paths", async () => {
57
+ await fs.symlink(outside, path.join(allowed, "link"));
58
+ expect(await canonicalizePath(path.join(allowed, "link", "a", "b.txt"))).toBe(
59
+ path.join(outside, "a", "b.txt")
60
+ );
61
+ });
62
+ it("follows dangling symlinks, including relative ones", async () => {
63
+ await fs.symlink(path.join(outside, "missing.txt"), path.join(allowed, "abs"));
64
+ await fs.symlink("../outside/rel.txt", path.join(allowed, "rel"));
65
+ expect(await canonicalizePath(path.join(allowed, "abs"))).toBe(
66
+ path.join(outside, "missing.txt")
67
+ );
68
+ expect(await canonicalizePath(path.join(allowed, "rel"))).toBe(
69
+ path.join(outside, "rel.txt")
70
+ );
71
+ });
72
+ it("follows chains of dangling symlinks", async () => {
73
+ await fs.symlink(path.join(outside, "end.txt"), path.join(allowed, "b"));
74
+ await fs.symlink(path.join(allowed, "b"), path.join(allowed, "a"));
75
+ expect(await canonicalizePath(path.join(allowed, "a"))).toBe(
76
+ path.join(outside, "end.txt")
77
+ );
78
+ });
79
+ it("rejects symlink loops", async () => {
80
+ await fs.symlink(path.join(allowed, "loop-b"), path.join(allowed, "loop-a"));
81
+ await fs.symlink(path.join(allowed, "loop-a"), path.join(allowed, "loop-b"));
82
+ await expect(canonicalizePath(path.join(allowed, "loop-a", "x"))).rejects.toThrow();
83
+ });
84
+ });
85
+ describe("PathValidator", () => {
86
+ it("rejects new paths that resolve outside through a directory symlink", async () => {
87
+ await fs.symlink(outside, path.join(allowed, "link"));
88
+ const validator = new PathValidator(config(), createMockLogger());
89
+ const result = await validator.validatePath("link/new.txt", "write");
90
+ expect(result.isValid).toBe(false);
91
+ });
92
+ it("rejects dangling symlinks that point outside", async () => {
93
+ await fs.symlink(path.join(outside, "x.txt"), path.join(allowed, "dangling"));
94
+ const validator = new PathValidator(config(), createMockLogger());
95
+ expect((await validator.validatePath("dangling", "write")).isValid).toBe(false);
96
+ expect(await validator.isPathWithinAllowed("dangling")).toBe(false);
97
+ });
98
+ it("accepts new files under an allowed root reached through a symlink", async () => {
99
+ const linkedRoot = path.join(root, "linked-root");
100
+ await fs.symlink(allowed, linkedRoot);
101
+ const validator = new PathValidator(config([linkedRoot]), createMockLogger());
102
+ const result = await validator.validatePath(path.join(linkedRoot, "new.txt"), "write");
103
+ expect(result.isValid).toBe(true);
104
+ expect(result.normalizedPath).toBe(path.join(allowed, "new.txt"));
105
+ });
106
+ it("rejects paths that a blocked path matches only lexically", async () => {
107
+ await fs.mkdir(path.join(allowed, "real-secret"));
108
+ await fs.symlink(path.join(allowed, "real-secret"), path.join(allowed, "secret"));
109
+ const validator = new PathValidator(
110
+ { ...config(), blockedPaths: [path.join(allowed, "secret")] },
111
+ createMockLogger()
112
+ );
113
+ expect((await validator.validatePath("secret/new.txt", "write")).isValid).toBe(false);
114
+ });
115
+ });
116
+ describe("FileSystemService writes", () => {
117
+ it("does not create files outside through a directory symlink", async () => {
118
+ await fs.symlink(outside, path.join(allowed, "link"));
119
+ const service = new FileSystemService(config(), createMockLogger());
120
+ await expect(service.writeFile("link/new.txt", "x")).rejects.toThrow();
121
+ await expect(service.writeFile("link/sub/deep.txt", "x")).rejects.toThrow();
122
+ expect(await listOutside()).toEqual([]);
123
+ });
124
+ it("does not create files outside through a dangling symlink", async () => {
125
+ await fs.symlink(path.join(outside, "x.txt"), path.join(allowed, "dangling"));
126
+ const service = new FileSystemService(config(), createMockLogger());
127
+ await expect(service.writeFile("dangling", "x")).rejects.toThrow();
128
+ expect(await listOutside()).toEqual([]);
129
+ });
130
+ it("writes the target of a dangling symlink that stays inside", async () => {
131
+ await fs.mkdir(path.join(allowed, "sub"));
132
+ await fs.symlink(path.join(allowed, "sub", "target.txt"), path.join(allowed, "link"));
133
+ const service = new FileSystemService(config(), createMockLogger());
134
+ const result = await service.writeFile("link", "inside");
135
+ expect(result.path).toBe(path.join(allowed, "sub", "target.txt"));
136
+ expect(await fs.readFile(path.join(allowed, "sub", "target.txt"), "utf-8")).toBe(
137
+ "inside"
138
+ );
139
+ });
140
+ it("does not edit files outside through a symlink", async () => {
141
+ await fs.writeFile(path.join(outside, "f.txt"), "old");
142
+ await fs.symlink(path.join(outside, "f.txt"), path.join(allowed, "f.txt"));
143
+ const service = new FileSystemService(config(), createMockLogger());
144
+ await expect(
145
+ service.editFile("f.txt", { oldString: "old", newString: "new" })
146
+ ).rejects.toThrow();
147
+ expect(await fs.readFile(path.join(outside, "f.txt"), "utf-8")).toBe("old");
148
+ });
149
+ it("still writes and overwrites regular files inside allowed paths", async () => {
150
+ const service = new FileSystemService(config(), createMockLogger());
151
+ await service.writeFile("dir/a.txt", "first");
152
+ await service.writeFile("dir/a.txt", "second");
153
+ expect(await fs.readFile(path.join(allowed, "dir", "a.txt"), "utf-8")).toBe("second");
154
+ });
155
+ });
156
+ describe("writeFileNoFollow (path swapped after validation)", () => {
157
+ const insideAllowed = (candidate) => {
158
+ const relative = path.relative(allowed, candidate);
159
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
160
+ };
161
+ it("refuses when the final component became a symlink", async () => {
162
+ await fs.writeFile(path.join(outside, "victim.txt"), "original");
163
+ const target = path.join(allowed, "file.txt");
164
+ await fs.symlink(path.join(outside, "victim.txt"), target);
165
+ await expect(
166
+ writeFileNoFollow(target, "clobbered", "utf-8", insideAllowed)
167
+ ).rejects.toThrow();
168
+ expect(await fs.readFile(path.join(outside, "victim.txt"), "utf-8")).toBe("original");
169
+ });
170
+ it("refuses and does not truncate when a parent directory became a symlink", async () => {
171
+ await fs.writeFile(path.join(outside, "victim.txt"), "original");
172
+ const target = path.join(allowed, "sub", "victim.txt");
173
+ await fs.symlink(outside, path.join(allowed, "sub"));
174
+ await expect(
175
+ writeFileNoFollow(target, "clobbered", "utf-8", insideAllowed)
176
+ ).rejects.toThrow(/changed during/);
177
+ expect(await fs.readFile(path.join(outside, "victim.txt"), "utf-8")).toBe("original");
178
+ });
179
+ it("truncates existing content on a normal overwrite", async () => {
180
+ const target = path.join(allowed, "f.txt");
181
+ await fs.writeFile(target, "a much longer original");
182
+ await writeFileNoFollow(target, "short", "utf-8", insideAllowed);
183
+ expect(await fs.readFile(target, "utf-8")).toBe("short");
184
+ });
185
+ it("removes a file it created when post-open verification fails", async () => {
186
+ const target = path.join(allowed, "new.txt");
187
+ await expect(writeFileNoFollow(target, "x", "utf-8", () => false)).rejects.toThrow(
188
+ /changed during/
189
+ );
190
+ await expect(fs.lstat(target)).rejects.toThrow();
191
+ });
192
+ it("does not create directories through a swapped parent", async () => {
193
+ await fs.symlink(outside, path.join(allowed, "sub"));
194
+ await expect(
195
+ writeFileNoFollow(
196
+ path.join(allowed, "sub", "deeper", "f.txt"),
197
+ "x",
198
+ "utf-8",
199
+ insideAllowed
200
+ )
201
+ ).rejects.toThrow();
202
+ expect(await listOutside()).toEqual([]);
203
+ });
204
+ });
205
+ describe("roots and blocked paths behind symlinks", () => {
206
+ it("blocks a relative blocked path reached through an alias when the root is behind a symlink", async () => {
207
+ const realBase = path.join(root, "real");
208
+ await fs.mkdir(path.join(realBase, "proj", ".git"), { recursive: true });
209
+ await fs.symlink(realBase, path.join(root, "tmp"));
210
+ const lexicalRoot = path.join(root, "tmp", "proj");
211
+ await fs.symlink(
212
+ path.join(realBase, "proj", ".git"),
213
+ path.join(realBase, "proj", "alias")
214
+ );
215
+ const validator = new PathValidator(
216
+ {
217
+ ...config([lexicalRoot]),
218
+ workingDirectory: lexicalRoot,
219
+ blockedPaths: [".git"]
220
+ },
221
+ createMockLogger()
222
+ );
223
+ expect((await validator.validatePath(".git/config", "write")).isValid).toBe(false);
224
+ expect((await validator.validatePath("alias/config", "write")).isValid).toBe(false);
225
+ expect((await validator.validatePath("alias/pre-commit", "write")).isValid).toBe(false);
226
+ expect((await validator.validatePath("src/new.ts", "write")).isValid).toBe(true);
227
+ });
228
+ it("does not widen allowed paths when a symlink is planted at a root later", async () => {
229
+ const futureRoot = path.join(root, "future");
230
+ const validator = new PathValidator(config([futureRoot]), createMockLogger());
231
+ expect(
232
+ (await validator.validatePath(path.join(futureRoot, "a.txt"), "write")).isValid
233
+ ).toBe(true);
234
+ await fs.symlink(outside, futureRoot);
235
+ const escaped = await validator.validatePath(path.join(outside, "x.txt"), "write");
236
+ expect(escaped.isValid).toBe(false);
237
+ const throughRoot = await validator.validatePath(
238
+ path.join(futureRoot, "x.txt"),
239
+ "write"
240
+ );
241
+ expect(throughRoot.isValid).toBe(false);
242
+ });
243
+ it("accepts deep new paths (more than 40 levels)", async () => {
244
+ const deep = path.join(...Array.from({ length: 50 }, (_, i) => `d${i}`), "f.txt");
245
+ const validator = new PathValidator(config(), createMockLogger());
246
+ expect((await validator.validatePath(deep, "write")).isValid).toBe(true);
247
+ });
248
+ });
249
+ describe("delete and rename act on links themselves", () => {
250
+ it("deletes a dangling symlink that points outside without touching the target", async () => {
251
+ await fs.symlink(path.join(outside, "missing.txt"), path.join(allowed, "dangling"));
252
+ const service = new FileSystemService(config(), createMockLogger());
253
+ await service.deletePath("dangling");
254
+ await expect(fs.lstat(path.join(allowed, "dangling"))).rejects.toThrow();
255
+ });
256
+ it("deletes a symlink, not the file it points to", async () => {
257
+ await fs.writeFile(path.join(allowed, "target.txt"), "keep");
258
+ await fs.symlink(path.join(allowed, "target.txt"), path.join(allowed, "link"));
259
+ const service = new FileSystemService(config(), createMockLogger());
260
+ await service.deletePath("link");
261
+ expect(await fs.readFile(path.join(allowed, "target.txt"), "utf-8")).toBe("keep");
262
+ });
263
+ it("refuses to move a file into a directory symlink that points outside", async () => {
264
+ await fs.writeFile(path.join(allowed, "f.txt"), "data");
265
+ await fs.symlink(outside, path.join(allowed, "link"));
266
+ const service = new FileSystemService(config(), createMockLogger());
267
+ await expect(service.renamePath("f.txt", "link/f.txt")).rejects.toThrow();
268
+ expect(await listOutside()).toEqual([]);
269
+ });
270
+ });
271
+ describe("directory approval", () => {
272
+ it("matches files under an approved directory reached through a symlink", async () => {
273
+ const linkedDir = path.join(root, "linked-outside");
274
+ await fs.symlink(outside, linkedDir);
275
+ const canonicalDir = await canonicalizePath(linkedDir);
276
+ const approvals = /* @__PURE__ */ new Map([
277
+ [createDirectoryApprovalKey(canonicalDir, "write"), "session"]
278
+ ]);
279
+ const validator = new PathValidator(config(), createMockLogger());
280
+ validator.setDirectoryApprovalChecker(
281
+ (filePath, operation) => isPathApprovedByDirectoryKey(filePath, approvals, void 0, operation)
282
+ );
283
+ const result = await validator.validatePath(path.join(linkedDir, "new.txt"), "write");
284
+ expect(result.isValid).toBe(true);
285
+ expect(result.normalizedPath).toBe(path.join(outside, "new.txt"));
286
+ });
287
+ });
288
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dexto/tools-filesystem",
3
- "version": "1.16.0",
3
+ "version": "1.16.2",
4
4
  "description": "FileSystem tools factory for Dexto agents",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -22,8 +22,8 @@
22
22
  "glob": "^14.0.3",
23
23
  "safe-regex": "^2.1.1",
24
24
  "zod": "^4.3.6",
25
- "@dexto/agent-config": "1.16.0",
26
- "@dexto/core": "1.16.0"
25
+ "@dexto/agent-config": "1.16.2",
26
+ "@dexto/core": "1.16.2"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/diff": "^5.2.3",