@dexto/tools-filesystem 1.15.0 → 1.16.1

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,71 @@
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 __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var backup_copy_exports = {};
30
+ __export(backup_copy_exports, {
31
+ assertSameFile: () => assertSameFile,
32
+ copyWithoutFollowingLinks: () => copyWithoutFollowingLinks
33
+ });
34
+ module.exports = __toCommonJS(backup_copy_exports);
35
+ var import_node_fs = require("node:fs");
36
+ var fs = __toESM(require("node:fs/promises"), 1);
37
+ var import_promises = require("node:stream/promises");
38
+ async function copyWithoutFollowingLinks(source, destination, platform = { noFollow: import_node_fs.constants.O_NOFOLLOW }) {
39
+ const linkStats = await fs.lstat(source);
40
+ if (!linkStats.isFile()) {
41
+ throw new Error("Only regular files can be backed up");
42
+ }
43
+ await platform.beforeOpen?.();
44
+ const input = await fs.open(source, import_node_fs.constants.O_RDONLY | (platform.noFollow ?? 0));
45
+ try {
46
+ const stats = await input.stat();
47
+ if (!stats.isFile()) {
48
+ throw new Error("Only regular files can be backed up");
49
+ }
50
+ assertSameFile(linkStats, stats, platform.noFollow !== void 0);
51
+ const output = await fs.open(destination, "wx", stats.mode & 511);
52
+ await (0, import_promises.pipeline)(input.createReadStream({ autoClose: false }), output.createWriteStream());
53
+ } finally {
54
+ await input.close();
55
+ }
56
+ }
57
+ function assertSameFile(linkStats, openedStats, hasNoFollow) {
58
+ if (!hasNoFollow && (linkStats.ino === 0 || openedStats.ino === 0)) {
59
+ throw new Error(
60
+ "Cannot safely back up on this platform: file identity is unavailable without O_NOFOLLOW"
61
+ );
62
+ }
63
+ if (linkStats.ino !== openedStats.ino || linkStats.dev !== openedStats.dev) {
64
+ throw new Error("Source changed while backing up");
65
+ }
66
+ }
67
+ // Annotate the CommonJS export names for ESM import in node:
68
+ 0 && (module.exports = {
69
+ assertSameFile,
70
+ copyWithoutFollowingLinks
71
+ });
@@ -0,0 +1,21 @@
1
+ import { type Stats } from 'node:fs';
2
+ export type BackupCopyPlatform = {
3
+ /** `O_NOFOLLOW`, which does not exist on Windows. */
4
+ noFollow: number | undefined;
5
+ /** Runs between the `lstat` and the open. Tests use it to swap the source deterministically. */
6
+ beforeOpen?: () => Promise<void>;
7
+ };
8
+ /**
9
+ * Copy a regular file without following a symlink at either end. An existing destination
10
+ * (including a symlink) fails with EEXIST, so a backup never writes outside the paths it was
11
+ * given.
12
+ *
13
+ * `lstat` refuses a symlink or junction up front. Where `O_NOFOLLOW` exists the open also refuses
14
+ * a link. Where it does not (Windows), a link swapped in after the `lstat` would be followed, so
15
+ * the opened descriptor must be the very file `lstat` saw (same device and inode), and a
16
+ * filesystem that reports no inode cannot prove that: the backup is refused.
17
+ */
18
+ export declare function copyWithoutFollowingLinks(source: string, destination: string, platform?: BackupCopyPlatform): Promise<void>;
19
+ /** Throws unless the opened file is the one `lstat` saw. Size and mtime are not an identity. */
20
+ export declare function assertSameFile(linkStats: Pick<Stats, 'dev' | 'ino'>, openedStats: Pick<Stats, 'dev' | 'ino'>, hasNoFollow: boolean): void;
21
+ //# sourceMappingURL=backup-copy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup-copy.d.ts","sourceRoot":"","sources":["../src/backup-copy.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,KAAK,EAAE,MAAM,SAAS,CAAC;AAI/D,MAAM,MAAM,kBAAkB,GAAG;IAC7B,qDAAqD;IACrD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,gGAAgG;IAChG,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,yBAAyB,CAC3C,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,QAAQ,GAAE,kBAAyD,GACpE,OAAO,CAAC,IAAI,CAAC,CAmBf;AAED,gGAAgG;AAChG,wBAAgB,cAAc,CAC1B,SAAS,EAAE,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,KAAK,CAAC,EACrC,WAAW,EAAE,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,KAAK,CAAC,EACvC,WAAW,EAAE,OAAO,GACrB,IAAI,CASN"}
@@ -0,0 +1,36 @@
1
+ import { constants as fsConstants } from "node:fs";
2
+ import * as fs from "node:fs/promises";
3
+ import { pipeline } from "node:stream/promises";
4
+ async function copyWithoutFollowingLinks(source, destination, platform = { noFollow: fsConstants.O_NOFOLLOW }) {
5
+ const linkStats = await fs.lstat(source);
6
+ if (!linkStats.isFile()) {
7
+ throw new Error("Only regular files can be backed up");
8
+ }
9
+ await platform.beforeOpen?.();
10
+ const input = await fs.open(source, fsConstants.O_RDONLY | (platform.noFollow ?? 0));
11
+ try {
12
+ const stats = await input.stat();
13
+ if (!stats.isFile()) {
14
+ throw new Error("Only regular files can be backed up");
15
+ }
16
+ assertSameFile(linkStats, stats, platform.noFollow !== void 0);
17
+ const output = await fs.open(destination, "wx", stats.mode & 511);
18
+ await pipeline(input.createReadStream({ autoClose: false }), output.createWriteStream());
19
+ } finally {
20
+ await input.close();
21
+ }
22
+ }
23
+ function assertSameFile(linkStats, openedStats, hasNoFollow) {
24
+ if (!hasNoFollow && (linkStats.ino === 0 || openedStats.ino === 0)) {
25
+ throw new Error(
26
+ "Cannot safely back up on this platform: file identity is unavailable without O_NOFOLLOW"
27
+ );
28
+ }
29
+ if (linkStats.ino !== openedStats.ino || linkStats.dev !== openedStats.dev) {
30
+ throw new Error("Source changed while backing up");
31
+ }
32
+ }
33
+ export {
34
+ assertSameFile,
35
+ copyWithoutFollowingLinks
36
+ };
@@ -0,0 +1,120 @@
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 import_node_fs = require("node:fs");
26
+ var fs = __toESM(require("node:fs/promises"), 1);
27
+ var os = __toESM(require("node:os"), 1);
28
+ var path = __toESM(require("node:path"), 1);
29
+ var import_backup_copy = require("./backup-copy.js");
30
+ (0, import_vitest.describe)("copyWithoutFollowingLinks", () => {
31
+ let dir;
32
+ let source;
33
+ let destination;
34
+ (0, import_vitest.beforeEach)(async () => {
35
+ dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "dexto-backup-copy-")));
36
+ source = path.join(dir, "source.txt");
37
+ destination = path.join(dir, "backup.txt");
38
+ await fs.writeFile(source, "original");
39
+ });
40
+ (0, import_vitest.afterEach)(async () => {
41
+ await fs.rm(dir, { recursive: true, force: true });
42
+ });
43
+ (0, import_vitest.describe)("without O_NOFOLLOW (Windows)", () => {
44
+ const noFollow = void 0;
45
+ (0, import_vitest.it)("copies a regular file", async () => {
46
+ await (0, import_backup_copy.copyWithoutFollowingLinks)(source, destination, { noFollow });
47
+ (0, import_vitest.expect)(await fs.readFile(destination, "utf-8")).toBe("original");
48
+ });
49
+ (0, import_vitest.it)("refuses a source swapped for a different file after the lstat", async () => {
50
+ const other = path.join(dir, "other.txt");
51
+ await fs.writeFile(other, "a different file");
52
+ await (0, import_vitest.expect)(
53
+ (0, import_backup_copy.copyWithoutFollowingLinks)(source, destination, {
54
+ noFollow,
55
+ beforeOpen: () => fs.rename(other, source)
56
+ })
57
+ ).rejects.toThrow("Source changed while backing up");
58
+ await (0, import_vitest.expect)(fs.access(destination)).rejects.toThrow();
59
+ });
60
+ (0, import_vitest.it)("refuses the swap even when size and mtime match", async () => {
61
+ const before = await fs.stat(source);
62
+ const other = path.join(dir, "other.txt");
63
+ await fs.writeFile(other, "ORIGINAL");
64
+ await fs.utimes(other, before.atime, before.mtime);
65
+ (0, import_vitest.expect)((await fs.stat(other)).size).toBe(before.size);
66
+ (0, import_vitest.expect)((await fs.stat(other)).mtime.getTime()).toBe(before.mtime.getTime());
67
+ await (0, import_vitest.expect)(
68
+ (0, import_backup_copy.copyWithoutFollowingLinks)(source, destination, {
69
+ noFollow,
70
+ beforeOpen: () => fs.rename(other, source)
71
+ })
72
+ ).rejects.toThrow("Source changed while backing up");
73
+ await (0, import_vitest.expect)(fs.access(destination)).rejects.toThrow();
74
+ });
75
+ (0, import_vitest.it)("refuses a symlink source", async () => {
76
+ const link = path.join(dir, "link.txt");
77
+ await fs.symlink(source, link);
78
+ await (0, import_vitest.expect)(
79
+ (0, import_backup_copy.copyWithoutFollowingLinks)(link, destination, { noFollow })
80
+ ).rejects.toThrow("Only regular files can be backed up");
81
+ });
82
+ });
83
+ (0, import_vitest.it)("refuses a symlink swapped in after the lstat where O_NOFOLLOW exists", async () => {
84
+ const outside = path.join(dir, "outside.txt");
85
+ await fs.writeFile(outside, "outside secret");
86
+ await (0, import_vitest.expect)(
87
+ (0, import_backup_copy.copyWithoutFollowingLinks)(source, destination, {
88
+ noFollow: import_node_fs.constants.O_NOFOLLOW,
89
+ beforeOpen: async () => {
90
+ await fs.rm(source);
91
+ await fs.symlink(outside, source);
92
+ }
93
+ })
94
+ ).rejects.toThrow();
95
+ await (0, import_vitest.expect)(fs.access(destination)).rejects.toThrow();
96
+ });
97
+ });
98
+ (0, import_vitest.describe)("assertSameFile", () => {
99
+ (0, import_vitest.it)("refuses when O_NOFOLLOW is missing and the lstat reports no inode", () => {
100
+ (0, import_vitest.expect)(() => (0, import_backup_copy.assertSameFile)({ dev: 1, ino: 0 }, { dev: 1, ino: 0 }, false)).toThrow(
101
+ /Cannot safely back up on this platform/
102
+ );
103
+ });
104
+ (0, import_vitest.it)("refuses when O_NOFOLLOW is missing and the opened file reports no inode", () => {
105
+ (0, import_vitest.expect)(() => (0, import_backup_copy.assertSameFile)({ dev: 1, ino: 7 }, { dev: 1, ino: 0 }, false)).toThrow(
106
+ /Cannot safely back up on this platform/
107
+ );
108
+ });
109
+ (0, import_vitest.it)("refuses a different inode or device", () => {
110
+ (0, import_vitest.expect)(() => (0, import_backup_copy.assertSameFile)({ dev: 1, ino: 7 }, { dev: 1, ino: 8 }, false)).toThrow(
111
+ "Source changed while backing up"
112
+ );
113
+ (0, import_vitest.expect)(() => (0, import_backup_copy.assertSameFile)({ dev: 1, ino: 7 }, { dev: 2, ino: 7 }, false)).toThrow(
114
+ "Source changed while backing up"
115
+ );
116
+ });
117
+ (0, import_vitest.it)("accepts the same inode and device", () => {
118
+ (0, import_vitest.expect)(() => (0, import_backup_copy.assertSameFile)({ dev: 1, ino: 7 }, { dev: 1, ino: 7 }, false)).not.toThrow();
119
+ });
120
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=backup-copy.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup-copy.test.d.ts","sourceRoot":"","sources":["../src/backup-copy.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,97 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
2
+ import { constants as fsConstants } from "node:fs";
3
+ import * as fs from "node:fs/promises";
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+ import { assertSameFile, copyWithoutFollowingLinks } from "./backup-copy.js";
7
+ describe("copyWithoutFollowingLinks", () => {
8
+ let dir;
9
+ let source;
10
+ let destination;
11
+ beforeEach(async () => {
12
+ dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "dexto-backup-copy-")));
13
+ source = path.join(dir, "source.txt");
14
+ destination = path.join(dir, "backup.txt");
15
+ await fs.writeFile(source, "original");
16
+ });
17
+ afterEach(async () => {
18
+ await fs.rm(dir, { recursive: true, force: true });
19
+ });
20
+ describe("without O_NOFOLLOW (Windows)", () => {
21
+ const noFollow = void 0;
22
+ it("copies a regular file", async () => {
23
+ await copyWithoutFollowingLinks(source, destination, { noFollow });
24
+ expect(await fs.readFile(destination, "utf-8")).toBe("original");
25
+ });
26
+ it("refuses a source swapped for a different file after the lstat", async () => {
27
+ const other = path.join(dir, "other.txt");
28
+ await fs.writeFile(other, "a different file");
29
+ await expect(
30
+ copyWithoutFollowingLinks(source, destination, {
31
+ noFollow,
32
+ beforeOpen: () => fs.rename(other, source)
33
+ })
34
+ ).rejects.toThrow("Source changed while backing up");
35
+ await expect(fs.access(destination)).rejects.toThrow();
36
+ });
37
+ it("refuses the swap even when size and mtime match", async () => {
38
+ const before = await fs.stat(source);
39
+ const other = path.join(dir, "other.txt");
40
+ await fs.writeFile(other, "ORIGINAL");
41
+ await fs.utimes(other, before.atime, before.mtime);
42
+ expect((await fs.stat(other)).size).toBe(before.size);
43
+ expect((await fs.stat(other)).mtime.getTime()).toBe(before.mtime.getTime());
44
+ await expect(
45
+ copyWithoutFollowingLinks(source, destination, {
46
+ noFollow,
47
+ beforeOpen: () => fs.rename(other, source)
48
+ })
49
+ ).rejects.toThrow("Source changed while backing up");
50
+ await expect(fs.access(destination)).rejects.toThrow();
51
+ });
52
+ it("refuses a symlink source", async () => {
53
+ const link = path.join(dir, "link.txt");
54
+ await fs.symlink(source, link);
55
+ await expect(
56
+ copyWithoutFollowingLinks(link, destination, { noFollow })
57
+ ).rejects.toThrow("Only regular files can be backed up");
58
+ });
59
+ });
60
+ it("refuses a symlink swapped in after the lstat where O_NOFOLLOW exists", async () => {
61
+ const outside = path.join(dir, "outside.txt");
62
+ await fs.writeFile(outside, "outside secret");
63
+ await expect(
64
+ copyWithoutFollowingLinks(source, destination, {
65
+ noFollow: fsConstants.O_NOFOLLOW,
66
+ beforeOpen: async () => {
67
+ await fs.rm(source);
68
+ await fs.symlink(outside, source);
69
+ }
70
+ })
71
+ ).rejects.toThrow();
72
+ await expect(fs.access(destination)).rejects.toThrow();
73
+ });
74
+ });
75
+ describe("assertSameFile", () => {
76
+ it("refuses when O_NOFOLLOW is missing and the lstat reports no inode", () => {
77
+ expect(() => assertSameFile({ dev: 1, ino: 0 }, { dev: 1, ino: 0 }, false)).toThrow(
78
+ /Cannot safely back up on this platform/
79
+ );
80
+ });
81
+ it("refuses when O_NOFOLLOW is missing and the opened file reports no inode", () => {
82
+ expect(() => assertSameFile({ dev: 1, ino: 7 }, { dev: 1, ino: 0 }, false)).toThrow(
83
+ /Cannot safely back up on this platform/
84
+ );
85
+ });
86
+ it("refuses a different inode or device", () => {
87
+ expect(() => assertSameFile({ dev: 1, ino: 7 }, { dev: 1, ino: 8 }, false)).toThrow(
88
+ "Source changed while backing up"
89
+ );
90
+ expect(() => assertSameFile({ dev: 1, ino: 7 }, { dev: 2, ino: 7 }, false)).toThrow(
91
+ "Source changed while backing up"
92
+ );
93
+ });
94
+ it("accepts the same inode and device", () => {
95
+ expect(() => assertSameFile({ dev: 1, ino: 7 }, { dev: 1, ino: 7 }, false)).not.toThrow();
96
+ });
97
+ });
@@ -37,6 +37,7 @@ module.exports = __toCommonJS(directory_approval_exports);
37
37
  var path = __toESM(require("node:path"), 1);
38
38
  var import_tools = require("@dexto/core/tools");
39
39
  var import_path_utils = require("./path-utils.js");
40
+ var import_safe_fs = require("./safe-fs.js");
40
41
  const DIRECTORY_APPROVAL_KEY_PREFIX = "directory:";
41
42
  const DIRECTORY_APPROVAL_OPERATION_SEPARATOR = ":operation:";
42
43
  function createDirectoryApprovalKey(directoryPath, operation) {
@@ -62,7 +63,7 @@ function isPathApprovedByDirectoryKey(filePath, approvedKeys, approvedTypes = /*
62
63
  continue;
63
64
  }
64
65
  const relative = path.relative(approvedDir, resolvedFilePath);
65
- if (!relative.startsWith("..") && !path.isAbsolute(relative)) {
66
+ if (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) {
66
67
  return true;
67
68
  }
68
69
  }
@@ -76,7 +77,12 @@ function createDirectoryAccessApprovalHandlers(options) {
76
77
  return {
77
78
  async needsApproval(input, context) {
78
79
  const resolvedFileSystemService = await options.getFileSystemService(context);
79
- const paths = options.resolvePaths(input, resolvedFileSystemService);
80
+ const lexicalPaths = options.resolvePaths(input, resolvedFileSystemService);
81
+ const canonicalPath = await (0, import_safe_fs.canonicalizePath)(lexicalPaths.path);
82
+ const paths = canonicalPath === lexicalPaths.path ? lexicalPaths : {
83
+ path: canonicalPath,
84
+ parentDir: lexicalPaths.parentDir === lexicalPaths.path ? canonicalPath : path.dirname(canonicalPath)
85
+ };
80
86
  const isAllowed = await resolvedFileSystemService.isPathWithinConfigAllowed(paths.path);
81
87
  if (isAllowed) {
82
88
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"directory-approval.d.ts","sourceRoot":"","sources":["../src/directory-approval.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,CAAC,EAAE,UAAU,EAAE,MAAM,KAAK,CAAC;AAEzC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAGpE,KAAK,0BAA0B,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAE5D,KAAK,sBAAsB,GAAG;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CACrB,CAAC;AAKF,wBAAgB,0BAA0B,CACtC,aAAa,EAAE,MAAM,EACrB,SAAS,CAAC,EAAE,0BAA0B,GACvC,MAAM,CAKR;AAED,wBAAgB,4BAA4B,CACxC,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,WAAW,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,CAAC,EACrD,aAAa,GAAE,WAAW,CAAC,SAAS,GAAG,MAAM,CAAgC,EAC7E,SAAS,CAAC,EAAE,0BAA0B,GACvC,OAAO,CA4BT;AAED,wBAAgB,eAAe,CAC3B,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,GACjB,sBAAsB,C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AAS,GAAG,MAAM,CAAgC,EAC7E,SAAS,CAAC,EAAE,0BAA0B,GACvC,OAAO,CAgCT;AAED,wBAAgB,eAAe,CAC3B,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,GACjB,sBAAsB,CAGxB;AAED,wBAAgB,qCAAqC,CAAC,KAAK,CAAC,OAAO,SAAS,UAAU,EAAE,OAAO,EAAE;IAC7F,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,0BAA0B,CAAC;IACtC,WAAW,EAAE,OAAO,CAAC;IACrB,oBAAoB,EAAE,uBAAuB,CAAC;IAC9C,YAAY,EAAE,CACV,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,EACxB,iBAAiB,EAAE,iBAAiB,KACnC,sBAAsB,CAAC;CAC/B,GAAG;IACA,aAAa,EAAE,CACX,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,EACxB,OAAO,EAAE,oBAAoB,KAC5B,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC;CAChC,CA6CA"}
@@ -1,6 +1,7 @@
1
1
  import * as path from "node:path";
2
2
  import { ToolError } from "@dexto/core/tools";
3
3
  import { resolveUserPath } from "./path-utils.js";
4
+ import { canonicalizePath } from "./safe-fs.js";
4
5
  const DIRECTORY_APPROVAL_KEY_PREFIX = "directory:";
5
6
  const DIRECTORY_APPROVAL_OPERATION_SEPARATOR = ":operation:";
6
7
  function createDirectoryApprovalKey(directoryPath, operation) {
@@ -26,7 +27,7 @@ function isPathApprovedByDirectoryKey(filePath, approvedKeys, approvedTypes = /*
26
27
  continue;
27
28
  }
28
29
  const relative = path.relative(approvedDir, resolvedFilePath);
29
- if (!relative.startsWith("..") && !path.isAbsolute(relative)) {
30
+ if (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) {
30
31
  return true;
31
32
  }
32
33
  }
@@ -40,7 +41,12 @@ function createDirectoryAccessApprovalHandlers(options) {
40
41
  return {
41
42
  async needsApproval(input, context) {
42
43
  const resolvedFileSystemService = await options.getFileSystemService(context);
43
- const paths = options.resolvePaths(input, resolvedFileSystemService);
44
+ const lexicalPaths = options.resolvePaths(input, resolvedFileSystemService);
45
+ const canonicalPath = await canonicalizePath(lexicalPaths.path);
46
+ const paths = canonicalPath === lexicalPaths.path ? lexicalPaths : {
47
+ path: canonicalPath,
48
+ parentDir: lexicalPaths.parentDir === lexicalPaths.path ? canonicalPath : path.dirname(canonicalPath)
49
+ };
44
50
  const isAllowed = await resolvedFileSystemService.isPathWithinConfigAllowed(paths.path);
45
51
  if (isAllowed) {
46
52
  return false;
@@ -38,10 +38,12 @@ var import_safe_regex = __toESM(require("safe-regex"), 1);
38
38
  var import_errors = require("@dexto/core/errors");
39
39
  var import_logger = require("@dexto/core/logger");
40
40
  var import_path = require("@dexto/core/utils/path.js");
41
+ var import_backup_copy = require("./backup-copy.js");
41
42
  var import_path_validator = require("./path-validator.js");
42
43
  var import_errors2 = require("./errors.js");
43
44
  var import_mime_utils = require("./mime-utils.js");
44
45
  var import_path_utils = require("./path-utils.js");
46
+ var import_safe_fs = require("./safe-fs.js");
45
47
  const DEFAULT_ENCODING = "utf-8";
46
48
  const DEFAULT_MAX_RESULTS = 1e3;
47
49
  const DEFAULT_MAX_SEARCH_RESULTS = 100;
@@ -541,9 +543,13 @@ class FileSystemService {
541
543
  const normalizedPath = validation.normalizedPath;
542
544
  const recursive = options.recursive ?? false;
543
545
  try {
544
- const firstCreated = await fs.mkdir(normalizedPath, { recursive });
545
- const created = recursive ? typeof firstCreated === "string" : true;
546
- return { path: normalizedPath, created };
546
+ if (recursive) {
547
+ const created = await (0, import_safe_fs.mkdirNoFollow)(normalizedPath);
548
+ return { path: normalizedPath, created };
549
+ }
550
+ await this.assertCanonicalUnchanged(path.dirname(normalizedPath));
551
+ await fs.mkdir(normalizedPath);
552
+ return { path: normalizedPath, created: true };
547
553
  } catch (error) {
548
554
  const code = error.code;
549
555
  if (code === "EEXIST") {
@@ -569,12 +575,15 @@ class FileSystemService {
569
575
  */
570
576
  async deletePath(targetPath, options = {}) {
571
577
  await this.ensureInitialized();
572
- const validation = await this.pathValidator.validatePath(targetPath, "write");
578
+ const validation = await this.pathValidator.validatePath(targetPath, "write", {
579
+ followFinalSymlink: false
580
+ });
573
581
  if (!validation.isValid || !validation.normalizedPath) {
574
582
  throw import_errors2.FileSystemError.invalidPath(targetPath, validation.error || "Unknown error");
575
583
  }
576
584
  const normalizedPath = validation.normalizedPath;
577
585
  try {
586
+ await this.assertCanonicalUnchanged(path.dirname(normalizedPath));
578
587
  await fs.rm(normalizedPath, { recursive: options.recursive ?? false, force: false });
579
588
  return { path: normalizedPath, deleted: true };
580
589
  } catch (error) {
@@ -596,11 +605,15 @@ class FileSystemService {
596
605
  */
597
606
  async renamePath(fromPath, toPath) {
598
607
  await this.ensureInitialized();
599
- const fromValidation = await this.pathValidator.validatePath(fromPath, "write");
608
+ const fromValidation = await this.pathValidator.validatePath(fromPath, "write", {
609
+ followFinalSymlink: false
610
+ });
600
611
  if (!fromValidation.isValid || !fromValidation.normalizedPath) {
601
612
  throw import_errors2.FileSystemError.invalidPath(fromPath, fromValidation.error || "Unknown error");
602
613
  }
603
- const toValidation = await this.pathValidator.validatePath(toPath, "write");
614
+ const toValidation = await this.pathValidator.validatePath(toPath, "write", {
615
+ followFinalSymlink: false
616
+ });
604
617
  if (!toValidation.isValid || !toValidation.normalizedPath) {
605
618
  throw import_errors2.FileSystemError.invalidPath(toPath, toValidation.error || "Unknown error");
606
619
  }
@@ -610,7 +623,7 @@ class FileSystemService {
610
623
  return { from: normalizedFrom, to: normalizedTo };
611
624
  }
612
625
  try {
613
- await fs.access(normalizedTo);
626
+ await fs.lstat(normalizedTo);
614
627
  throw import_errors2.FileSystemError.renameFailed(
615
628
  normalizedFrom,
616
629
  `Target already exists: ${normalizedTo}`
@@ -631,6 +644,8 @@ class FileSystemService {
631
644
  }
632
645
  }
633
646
  try {
647
+ await this.assertCanonicalUnchanged(path.dirname(normalizedFrom));
648
+ await this.assertCanonicalUnchanged(path.dirname(normalizedTo));
634
649
  await fs.rename(normalizedFrom, normalizedTo);
635
650
  return { from: normalizedFrom, to: normalizedTo };
636
651
  } catch (error) {
@@ -752,6 +767,15 @@ class FileSystemService {
752
767
  );
753
768
  }
754
769
  }
770
+ /**
771
+ * Throw if a validated canonical directory no longer resolves to itself, i.e. one of its
772
+ * components was replaced by a symlink after validation.
773
+ */
774
+ async assertCanonicalUnchanged(canonicalDir) {
775
+ if (await (0, import_safe_fs.canonicalizePath)(canonicalDir) !== canonicalDir) {
776
+ throw new Error(`Path changed during operation: ${canonicalDir}`);
777
+ }
778
+ }
755
779
  /**
756
780
  * Write content to a file
757
781
  */
@@ -774,9 +798,12 @@ class FileSystemService {
774
798
  backupPath = await this.createBackup(normalizedPath);
775
799
  }
776
800
  try {
777
- const dir = path.dirname(normalizedPath);
778
- await fs.mkdir(dir, { recursive: true });
779
- await fs.writeFile(normalizedPath, content, encoding);
801
+ await (0, import_safe_fs.writeFileNoFollow)(
802
+ normalizedPath,
803
+ content,
804
+ encoding,
805
+ (candidate) => this.pathValidator.isPathAllowedQuick(candidate, "write")
806
+ );
780
807
  const bytesWritten = Buffer.byteLength(content, encoding);
781
808
  this.logger.debug(`File written: ${normalizedPath} (${bytesWritten} bytes)`);
782
809
  return {
@@ -827,7 +854,12 @@ class FileSystemService {
827
854
  } else {
828
855
  newContent = originalContent.replace(operation.oldString, operation.newString);
829
856
  }
830
- await fs.writeFile(normalizedPath, newContent, options.encoding || DEFAULT_ENCODING);
857
+ await (0, import_safe_fs.writeFileNoFollow)(
858
+ normalizedPath,
859
+ newContent,
860
+ options.encoding || DEFAULT_ENCODING,
861
+ (candidate) => this.pathValidator.isPathAllowedQuick(candidate, "edit")
862
+ );
831
863
  this.logger.debug(`File edited: ${normalizedPath} (${occurrences} replacements)`);
832
864
  return {
833
865
  success: true,
@@ -855,7 +887,7 @@ class FileSystemService {
855
887
  const backupPath = path.join(backupDir, backupFilename);
856
888
  try {
857
889
  await fs.mkdir(backupDir, { recursive: true });
858
- await fs.copyFile(filePath, backupPath);
890
+ await (0, import_backup_copy.copyWithoutFollowingLinks)(filePath, backupPath);
859
891
  this.logger.debug(`Backup created: ${backupPath}`);
860
892
  await this.cleanupOldBackups();
861
893
  return backupPath;
@@ -118,6 +118,11 @@ export declare class FileSystemService {
118
118
  * Search for content in files (grep-like functionality)
119
119
  */
120
120
  searchContent(pattern: string, options?: GrepOptions): Promise<SearchResult>;
121
+ /**
122
+ * Throw if a validated canonical directory no longer resolves to itself, i.e. one of its
123
+ * components was replaced by a symlink after validation.
124
+ */
125
+ private assertCanonicalUnchanged;
121
126
  /**
122
127
  * Write content to a file
123
128
  */
@@ -1 +1 @@
1
- {"version":3,"file":"filesystem-service.d.ts","sourceRoot":"","sources":["../src/filesystem-service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAOH,OAAO,EAAqB,KAAK,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEpE,OAAO,EACH,gBAAgB,EAChB,WAAW,EACX,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,UAAU,EACV,WAAW,EACX,YAAY,EAEZ,gBAAgB,EAChB,WAAW,EACX,eAAe,EACf,UAAU,EACV,aAAa,EAGb,oBAAoB,EACpB,mBAAmB,EACnB,sBAAsB,EACtB,qBAAqB,EACrB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAEnB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAiB,KAAK,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AAWrF;;;;;;;;GAQG;AACH,qBAAa,iBAAiB;IAC1B,OAAO,CAAC,MAAM,CAAmB;IACjC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,WAAW,CAAkB;IACrC,OAAO,CAAC,WAAW,CAA8B;IACjD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,wBAAwB,CAAC,CAEjB;IAEhB;;;;;;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