@dexto/tools-filesystem 1.16.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.
- package/dist/backup-copy.cjs +71 -0
- package/dist/backup-copy.d.ts +21 -0
- package/dist/backup-copy.d.ts.map +1 -0
- package/dist/backup-copy.js +36 -0
- package/dist/backup-copy.test.cjs +120 -0
- package/dist/backup-copy.test.d.ts +2 -0
- package/dist/backup-copy.test.d.ts.map +1 -0
- package/dist/backup-copy.test.js +97 -0
- package/dist/directory-approval.cjs +8 -2
- package/dist/directory-approval.d.ts.map +1 -1
- package/dist/directory-approval.js +8 -2
- package/dist/filesystem-service.cjs +44 -12
- package/dist/filesystem-service.d.ts +5 -0
- package/dist/filesystem-service.d.ts.map +1 -1
- package/dist/filesystem-service.js +44 -12
- package/dist/filesystem-service.test.cjs +74 -0
- package/dist/filesystem-service.test.js +74 -0
- package/dist/index.d.cts +27 -1
- package/dist/path-validator.cjs +93 -31
- package/dist/path-validator.d.ts +22 -1
- package/dist/path-validator.d.ts.map +1 -1
- package/dist/path-validator.js +93 -31
- package/dist/safe-fs.cjs +184 -0
- package/dist/safe-fs.d.ts +45 -0
- package/dist/safe-fs.d.ts.map +1 -0
- package/dist/safe-fs.js +148 -0
- package/dist/safe-fs.test.cjs +311 -0
- package/dist/safe-fs.test.d.ts +5 -0
- package/dist/safe-fs.test.d.ts.map +1 -0
- package/dist/safe-fs.test.js +288 -0
- package/package.json +3 -3
|
@@ -5,10 +5,12 @@ import safeRegex from "safe-regex";
|
|
|
5
5
|
import { DextoRuntimeError } from "@dexto/core/errors";
|
|
6
6
|
import { DextoLogComponent } from "@dexto/core/logger";
|
|
7
7
|
import { getDextoPath } from "@dexto/core/utils/path.js";
|
|
8
|
+
import { copyWithoutFollowingLinks } from "./backup-copy.js";
|
|
8
9
|
import { PathValidator } from "./path-validator.js";
|
|
9
10
|
import { FileSystemError } from "./errors.js";
|
|
10
11
|
import { detectMimeType, getMediaFileKind, isLikelyBinary, isTextMimeType } from "./mime-utils.js";
|
|
11
12
|
import { resolveUserPath } from "./path-utils.js";
|
|
13
|
+
import { canonicalizePath, mkdirNoFollow, writeFileNoFollow } from "./safe-fs.js";
|
|
12
14
|
const DEFAULT_ENCODING = "utf-8";
|
|
13
15
|
const DEFAULT_MAX_RESULTS = 1e3;
|
|
14
16
|
const DEFAULT_MAX_SEARCH_RESULTS = 100;
|
|
@@ -508,9 +510,13 @@ class FileSystemService {
|
|
|
508
510
|
const normalizedPath = validation.normalizedPath;
|
|
509
511
|
const recursive = options.recursive ?? false;
|
|
510
512
|
try {
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
513
|
+
if (recursive) {
|
|
514
|
+
const created = await mkdirNoFollow(normalizedPath);
|
|
515
|
+
return { path: normalizedPath, created };
|
|
516
|
+
}
|
|
517
|
+
await this.assertCanonicalUnchanged(path.dirname(normalizedPath));
|
|
518
|
+
await fs.mkdir(normalizedPath);
|
|
519
|
+
return { path: normalizedPath, created: true };
|
|
514
520
|
} catch (error) {
|
|
515
521
|
const code = error.code;
|
|
516
522
|
if (code === "EEXIST") {
|
|
@@ -536,12 +542,15 @@ class FileSystemService {
|
|
|
536
542
|
*/
|
|
537
543
|
async deletePath(targetPath, options = {}) {
|
|
538
544
|
await this.ensureInitialized();
|
|
539
|
-
const validation = await this.pathValidator.validatePath(targetPath, "write"
|
|
545
|
+
const validation = await this.pathValidator.validatePath(targetPath, "write", {
|
|
546
|
+
followFinalSymlink: false
|
|
547
|
+
});
|
|
540
548
|
if (!validation.isValid || !validation.normalizedPath) {
|
|
541
549
|
throw FileSystemError.invalidPath(targetPath, validation.error || "Unknown error");
|
|
542
550
|
}
|
|
543
551
|
const normalizedPath = validation.normalizedPath;
|
|
544
552
|
try {
|
|
553
|
+
await this.assertCanonicalUnchanged(path.dirname(normalizedPath));
|
|
545
554
|
await fs.rm(normalizedPath, { recursive: options.recursive ?? false, force: false });
|
|
546
555
|
return { path: normalizedPath, deleted: true };
|
|
547
556
|
} catch (error) {
|
|
@@ -563,11 +572,15 @@ class FileSystemService {
|
|
|
563
572
|
*/
|
|
564
573
|
async renamePath(fromPath, toPath) {
|
|
565
574
|
await this.ensureInitialized();
|
|
566
|
-
const fromValidation = await this.pathValidator.validatePath(fromPath, "write"
|
|
575
|
+
const fromValidation = await this.pathValidator.validatePath(fromPath, "write", {
|
|
576
|
+
followFinalSymlink: false
|
|
577
|
+
});
|
|
567
578
|
if (!fromValidation.isValid || !fromValidation.normalizedPath) {
|
|
568
579
|
throw FileSystemError.invalidPath(fromPath, fromValidation.error || "Unknown error");
|
|
569
580
|
}
|
|
570
|
-
const toValidation = await this.pathValidator.validatePath(toPath, "write"
|
|
581
|
+
const toValidation = await this.pathValidator.validatePath(toPath, "write", {
|
|
582
|
+
followFinalSymlink: false
|
|
583
|
+
});
|
|
571
584
|
if (!toValidation.isValid || !toValidation.normalizedPath) {
|
|
572
585
|
throw FileSystemError.invalidPath(toPath, toValidation.error || "Unknown error");
|
|
573
586
|
}
|
|
@@ -577,7 +590,7 @@ class FileSystemService {
|
|
|
577
590
|
return { from: normalizedFrom, to: normalizedTo };
|
|
578
591
|
}
|
|
579
592
|
try {
|
|
580
|
-
await fs.
|
|
593
|
+
await fs.lstat(normalizedTo);
|
|
581
594
|
throw FileSystemError.renameFailed(
|
|
582
595
|
normalizedFrom,
|
|
583
596
|
`Target already exists: ${normalizedTo}`
|
|
@@ -598,6 +611,8 @@ class FileSystemService {
|
|
|
598
611
|
}
|
|
599
612
|
}
|
|
600
613
|
try {
|
|
614
|
+
await this.assertCanonicalUnchanged(path.dirname(normalizedFrom));
|
|
615
|
+
await this.assertCanonicalUnchanged(path.dirname(normalizedTo));
|
|
601
616
|
await fs.rename(normalizedFrom, normalizedTo);
|
|
602
617
|
return { from: normalizedFrom, to: normalizedTo };
|
|
603
618
|
} catch (error) {
|
|
@@ -719,6 +734,15 @@ class FileSystemService {
|
|
|
719
734
|
);
|
|
720
735
|
}
|
|
721
736
|
}
|
|
737
|
+
/**
|
|
738
|
+
* Throw if a validated canonical directory no longer resolves to itself, i.e. one of its
|
|
739
|
+
* components was replaced by a symlink after validation.
|
|
740
|
+
*/
|
|
741
|
+
async assertCanonicalUnchanged(canonicalDir) {
|
|
742
|
+
if (await canonicalizePath(canonicalDir) !== canonicalDir) {
|
|
743
|
+
throw new Error(`Path changed during operation: ${canonicalDir}`);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
722
746
|
/**
|
|
723
747
|
* Write content to a file
|
|
724
748
|
*/
|
|
@@ -741,9 +765,12 @@ class FileSystemService {
|
|
|
741
765
|
backupPath = await this.createBackup(normalizedPath);
|
|
742
766
|
}
|
|
743
767
|
try {
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
768
|
+
await writeFileNoFollow(
|
|
769
|
+
normalizedPath,
|
|
770
|
+
content,
|
|
771
|
+
encoding,
|
|
772
|
+
(candidate) => this.pathValidator.isPathAllowedQuick(candidate, "write")
|
|
773
|
+
);
|
|
747
774
|
const bytesWritten = Buffer.byteLength(content, encoding);
|
|
748
775
|
this.logger.debug(`File written: ${normalizedPath} (${bytesWritten} bytes)`);
|
|
749
776
|
return {
|
|
@@ -794,7 +821,12 @@ class FileSystemService {
|
|
|
794
821
|
} else {
|
|
795
822
|
newContent = originalContent.replace(operation.oldString, operation.newString);
|
|
796
823
|
}
|
|
797
|
-
await
|
|
824
|
+
await writeFileNoFollow(
|
|
825
|
+
normalizedPath,
|
|
826
|
+
newContent,
|
|
827
|
+
options.encoding || DEFAULT_ENCODING,
|
|
828
|
+
(candidate) => this.pathValidator.isPathAllowedQuick(candidate, "edit")
|
|
829
|
+
);
|
|
798
830
|
this.logger.debug(`File edited: ${normalizedPath} (${occurrences} replacements)`);
|
|
799
831
|
return {
|
|
800
832
|
success: true,
|
|
@@ -822,7 +854,7 @@ class FileSystemService {
|
|
|
822
854
|
const backupPath = path.join(backupDir, backupFilename);
|
|
823
855
|
try {
|
|
824
856
|
await fs.mkdir(backupDir, { recursive: true });
|
|
825
|
-
await
|
|
857
|
+
await copyWithoutFollowingLinks(filePath, backupPath);
|
|
826
858
|
this.logger.debug(`Backup created: ${backupPath}`);
|
|
827
859
|
await this.cleanupOldBackups();
|
|
828
860
|
return backupPath;
|
|
@@ -26,6 +26,16 @@ var path = __toESM(require("node:path"), 1);
|
|
|
26
26
|
var fs = __toESM(require("node:fs/promises"), 1);
|
|
27
27
|
var os = __toESM(require("node:os"), 1);
|
|
28
28
|
var import_filesystem_service = require("./filesystem-service.js");
|
|
29
|
+
const nodeFs = import_vitest.vi.hoisted(() => ({ hideNoFollow: false }));
|
|
30
|
+
import_vitest.vi.mock("node:fs", async (importOriginal) => {
|
|
31
|
+
const actual = await importOriginal();
|
|
32
|
+
const constants = { ...actual.constants };
|
|
33
|
+
Object.defineProperty(constants, "O_NOFOLLOW", {
|
|
34
|
+
enumerable: true,
|
|
35
|
+
get: () => nodeFs.hideNoFollow ? void 0 : actual.constants.O_NOFOLLOW
|
|
36
|
+
});
|
|
37
|
+
return { ...actual, constants };
|
|
38
|
+
});
|
|
29
39
|
const createMockLogger = () => {
|
|
30
40
|
const logger = {
|
|
31
41
|
debug: import_vitest.vi.fn(),
|
|
@@ -351,5 +361,69 @@ const createMockLogger = () => {
|
|
|
351
361
|
(0, import_vitest.expect)(result.backupPath).toBeDefined();
|
|
352
362
|
});
|
|
353
363
|
});
|
|
364
|
+
(0, import_vitest.describe)("symlinks are never followed", () => {
|
|
365
|
+
let outsideDir;
|
|
366
|
+
let service;
|
|
367
|
+
(0, import_vitest.beforeEach)(async () => {
|
|
368
|
+
outsideDir = await fs.realpath(
|
|
369
|
+
await fs.mkdtemp(path.join(os.tmpdir(), "dexto-fs-outside-"))
|
|
370
|
+
);
|
|
371
|
+
service = new import_filesystem_service.FileSystemService(
|
|
372
|
+
{
|
|
373
|
+
allowedPaths: [tempDir],
|
|
374
|
+
blockedPaths: [],
|
|
375
|
+
blockedExtensions: [],
|
|
376
|
+
maxFileSize: 10 * 1024 * 1024,
|
|
377
|
+
workingDirectory: tempDir,
|
|
378
|
+
enableBackups: true,
|
|
379
|
+
backupPath: backupDir,
|
|
380
|
+
backupRetentionDays: 7
|
|
381
|
+
},
|
|
382
|
+
mockLogger
|
|
383
|
+
);
|
|
384
|
+
await service.initialize();
|
|
385
|
+
});
|
|
386
|
+
(0, import_vitest.afterEach)(async () => {
|
|
387
|
+
import_vitest.vi.useRealTimers();
|
|
388
|
+
nodeFs.hideNoFollow = false;
|
|
389
|
+
await fs.rm(outsideDir, { recursive: true, force: true });
|
|
390
|
+
});
|
|
391
|
+
(0, import_vitest.it)("refuses to back up a symlink and copies nothing from its target", async () => {
|
|
392
|
+
const secret = path.join(outsideDir, "secret.txt");
|
|
393
|
+
await fs.writeFile(secret, "outside secret");
|
|
394
|
+
const link = path.join(tempDir, "link.txt");
|
|
395
|
+
await fs.symlink(secret, link);
|
|
396
|
+
await (0, import_vitest.expect)(service["createBackup"](link)).rejects.toThrow(/backup/i);
|
|
397
|
+
(0, import_vitest.expect)(await fs.readdir(backupDir)).toEqual([]);
|
|
398
|
+
});
|
|
399
|
+
(0, import_vitest.it)("refuses a symlink source where O_NOFOLLOW is unavailable (Windows)", async () => {
|
|
400
|
+
nodeFs.hideNoFollow = true;
|
|
401
|
+
const secret = path.join(outsideDir, "secret.txt");
|
|
402
|
+
await fs.writeFile(secret, "outside secret");
|
|
403
|
+
const link = path.join(tempDir, "link.txt");
|
|
404
|
+
await fs.symlink(secret, link);
|
|
405
|
+
await (0, import_vitest.expect)(service["createBackup"](link)).rejects.toThrow(/backup/i);
|
|
406
|
+
(0, import_vitest.expect)(await fs.readdir(backupDir)).toEqual([]);
|
|
407
|
+
});
|
|
408
|
+
(0, import_vitest.it)("still backs up a regular file where O_NOFOLLOW is unavailable (Windows)", async () => {
|
|
409
|
+
nodeFs.hideNoFollow = true;
|
|
410
|
+
const source = path.join(tempDir, "test.txt");
|
|
411
|
+
await fs.writeFile(source, "original content");
|
|
412
|
+
const backupPath = await service["createBackup"](source);
|
|
413
|
+
(0, import_vitest.expect)(await fs.readFile(backupPath, "utf-8")).toBe("original content");
|
|
414
|
+
});
|
|
415
|
+
(0, import_vitest.it)("does not write through a symlink planted at the backup path", async () => {
|
|
416
|
+
const victim = path.join(outsideDir, "victim.txt");
|
|
417
|
+
await fs.writeFile(victim, "victim content");
|
|
418
|
+
const source = path.join(tempDir, "test.txt");
|
|
419
|
+
await fs.writeFile(source, "original content");
|
|
420
|
+
import_vitest.vi.useFakeTimers({ toFake: ["Date"] });
|
|
421
|
+
import_vitest.vi.setSystemTime(/* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"));
|
|
422
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
423
|
+
await fs.symlink(victim, path.join(backupDir, `test.txt.${timestamp}.backup`));
|
|
424
|
+
await (0, import_vitest.expect)(service["createBackup"](source)).rejects.toThrow(/backup/i);
|
|
425
|
+
(0, import_vitest.expect)(await fs.readFile(victim, "utf-8")).toBe("victim content");
|
|
426
|
+
});
|
|
427
|
+
});
|
|
354
428
|
});
|
|
355
429
|
});
|
|
@@ -3,6 +3,16 @@ import * as path from "node:path";
|
|
|
3
3
|
import * as fs from "node:fs/promises";
|
|
4
4
|
import * as os from "node:os";
|
|
5
5
|
import { FileSystemService } from "./filesystem-service.js";
|
|
6
|
+
const nodeFs = vi.hoisted(() => ({ hideNoFollow: false }));
|
|
7
|
+
vi.mock("node:fs", async (importOriginal) => {
|
|
8
|
+
const actual = await importOriginal();
|
|
9
|
+
const constants = { ...actual.constants };
|
|
10
|
+
Object.defineProperty(constants, "O_NOFOLLOW", {
|
|
11
|
+
enumerable: true,
|
|
12
|
+
get: () => nodeFs.hideNoFollow ? void 0 : actual.constants.O_NOFOLLOW
|
|
13
|
+
});
|
|
14
|
+
return { ...actual, constants };
|
|
15
|
+
});
|
|
6
16
|
const createMockLogger = () => {
|
|
7
17
|
const logger = {
|
|
8
18
|
debug: vi.fn(),
|
|
@@ -328,5 +338,69 @@ describe("FileSystemService", () => {
|
|
|
328
338
|
expect(result.backupPath).toBeDefined();
|
|
329
339
|
});
|
|
330
340
|
});
|
|
341
|
+
describe("symlinks are never followed", () => {
|
|
342
|
+
let outsideDir;
|
|
343
|
+
let service;
|
|
344
|
+
beforeEach(async () => {
|
|
345
|
+
outsideDir = await fs.realpath(
|
|
346
|
+
await fs.mkdtemp(path.join(os.tmpdir(), "dexto-fs-outside-"))
|
|
347
|
+
);
|
|
348
|
+
service = new FileSystemService(
|
|
349
|
+
{
|
|
350
|
+
allowedPaths: [tempDir],
|
|
351
|
+
blockedPaths: [],
|
|
352
|
+
blockedExtensions: [],
|
|
353
|
+
maxFileSize: 10 * 1024 * 1024,
|
|
354
|
+
workingDirectory: tempDir,
|
|
355
|
+
enableBackups: true,
|
|
356
|
+
backupPath: backupDir,
|
|
357
|
+
backupRetentionDays: 7
|
|
358
|
+
},
|
|
359
|
+
mockLogger
|
|
360
|
+
);
|
|
361
|
+
await service.initialize();
|
|
362
|
+
});
|
|
363
|
+
afterEach(async () => {
|
|
364
|
+
vi.useRealTimers();
|
|
365
|
+
nodeFs.hideNoFollow = false;
|
|
366
|
+
await fs.rm(outsideDir, { recursive: true, force: true });
|
|
367
|
+
});
|
|
368
|
+
it("refuses to back up a symlink and copies nothing from its target", async () => {
|
|
369
|
+
const secret = path.join(outsideDir, "secret.txt");
|
|
370
|
+
await fs.writeFile(secret, "outside secret");
|
|
371
|
+
const link = path.join(tempDir, "link.txt");
|
|
372
|
+
await fs.symlink(secret, link);
|
|
373
|
+
await expect(service["createBackup"](link)).rejects.toThrow(/backup/i);
|
|
374
|
+
expect(await fs.readdir(backupDir)).toEqual([]);
|
|
375
|
+
});
|
|
376
|
+
it("refuses a symlink source where O_NOFOLLOW is unavailable (Windows)", async () => {
|
|
377
|
+
nodeFs.hideNoFollow = true;
|
|
378
|
+
const secret = path.join(outsideDir, "secret.txt");
|
|
379
|
+
await fs.writeFile(secret, "outside secret");
|
|
380
|
+
const link = path.join(tempDir, "link.txt");
|
|
381
|
+
await fs.symlink(secret, link);
|
|
382
|
+
await expect(service["createBackup"](link)).rejects.toThrow(/backup/i);
|
|
383
|
+
expect(await fs.readdir(backupDir)).toEqual([]);
|
|
384
|
+
});
|
|
385
|
+
it("still backs up a regular file where O_NOFOLLOW is unavailable (Windows)", async () => {
|
|
386
|
+
nodeFs.hideNoFollow = true;
|
|
387
|
+
const source = path.join(tempDir, "test.txt");
|
|
388
|
+
await fs.writeFile(source, "original content");
|
|
389
|
+
const backupPath = await service["createBackup"](source);
|
|
390
|
+
expect(await fs.readFile(backupPath, "utf-8")).toBe("original content");
|
|
391
|
+
});
|
|
392
|
+
it("does not write through a symlink planted at the backup path", async () => {
|
|
393
|
+
const victim = path.join(outsideDir, "victim.txt");
|
|
394
|
+
await fs.writeFile(victim, "victim content");
|
|
395
|
+
const source = path.join(tempDir, "test.txt");
|
|
396
|
+
await fs.writeFile(source, "original content");
|
|
397
|
+
vi.useFakeTimers({ toFake: ["Date"] });
|
|
398
|
+
vi.setSystemTime(/* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z"));
|
|
399
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
400
|
+
await fs.symlink(victim, path.join(backupDir, `test.txt.${timestamp}.backup`));
|
|
401
|
+
await expect(service["createBackup"](source)).rejects.toThrow(/backup/i);
|
|
402
|
+
expect(await fs.readFile(victim, "utf-8")).toBe("victim content");
|
|
403
|
+
});
|
|
404
|
+
});
|
|
331
405
|
});
|
|
332
406
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -325,6 +325,11 @@ type DirectoryApprovalChecker = (filePath: string, operation: DirectoryApprovalO
|
|
|
325
325
|
declare class PathValidator {
|
|
326
326
|
private config;
|
|
327
327
|
private normalizedAllowedPaths;
|
|
328
|
+
/** Canonical (symlink-resolved) forms of allowed roots, resolved once on first use. */
|
|
329
|
+
private canonicalAllowedPaths;
|
|
330
|
+
/** Blocked paths as absolute paths, in both lexical and canonical form. */
|
|
331
|
+
private resolvedBlockedPaths;
|
|
332
|
+
private canonicalPathsReady;
|
|
328
333
|
private normalizedBlockedPaths;
|
|
329
334
|
private normalizedBlockedExtensions;
|
|
330
335
|
private logger;
|
|
@@ -340,7 +345,9 @@ declare class PathValidator {
|
|
|
340
345
|
/**
|
|
341
346
|
* Validate a file path for security and policy compliance
|
|
342
347
|
*/
|
|
343
|
-
validatePath(filePath: string, operation: DirectoryApprovalOperation
|
|
348
|
+
validatePath(filePath: string, operation: DirectoryApprovalOperation, options?: {
|
|
349
|
+
followFinalSymlink?: boolean;
|
|
350
|
+
}): Promise<PathValidation>;
|
|
344
351
|
/**
|
|
345
352
|
* Validate a file path for preview purposes.
|
|
346
353
|
*
|
|
@@ -369,6 +376,11 @@ declare class PathValidator {
|
|
|
369
376
|
* Check if path matches blocked patterns (blacklist check)
|
|
370
377
|
*/
|
|
371
378
|
private isPathBlocked;
|
|
379
|
+
/**
|
|
380
|
+
* Resolve each blocked path to an absolute path: absolute entries as-is, relative entries
|
|
381
|
+
* against each of the given roots (or the working directory when no roots are configured).
|
|
382
|
+
*/
|
|
383
|
+
private resolveBlockedPaths;
|
|
372
384
|
/**
|
|
373
385
|
* Quick check if a path is allowed (for internal use)
|
|
374
386
|
* Note: This assumes the path is already normalized/canonicalized
|
|
@@ -395,6 +407,15 @@ declare class PathValidator {
|
|
|
395
407
|
* Used for prompting decisions.
|
|
396
408
|
*/
|
|
397
409
|
private isInConfigAllowedPaths;
|
|
410
|
+
/**
|
|
411
|
+
* Allowed roots and blocked paths are configured lexically, but validated paths are
|
|
412
|
+
* canonical. Resolve their canonical forms once, on first use, so a root reached through a
|
|
413
|
+
* symlink (for example macOS `/tmp` -> `/private/tmp`) still matches its own files and a
|
|
414
|
+
* blocked path reached through an alias is still blocked. Resolving only once means a
|
|
415
|
+
* symlink planted at a root location later cannot widen what is allowed.
|
|
416
|
+
*/
|
|
417
|
+
private ensureCanonicalPaths;
|
|
418
|
+
private resolveCanonicalPaths;
|
|
398
419
|
/**
|
|
399
420
|
* Get normalized allowed paths
|
|
400
421
|
*/
|
|
@@ -523,6 +544,11 @@ declare class FileSystemService {
|
|
|
523
544
|
* Search for content in files (grep-like functionality)
|
|
524
545
|
*/
|
|
525
546
|
searchContent(pattern: string, options?: GrepOptions): Promise<SearchResult>;
|
|
547
|
+
/**
|
|
548
|
+
* Throw if a validated canonical directory no longer resolves to itself, i.e. one of its
|
|
549
|
+
* components was replaced by a symlink after validation.
|
|
550
|
+
*/
|
|
551
|
+
private assertCanonicalUnchanged;
|
|
526
552
|
/**
|
|
527
553
|
* Write content to a file
|
|
528
554
|
*/
|
package/dist/path-validator.cjs
CHANGED
|
@@ -32,11 +32,16 @@ __export(path_validator_exports, {
|
|
|
32
32
|
});
|
|
33
33
|
module.exports = __toCommonJS(path_validator_exports);
|
|
34
34
|
var path = __toESM(require("node:path"), 1);
|
|
35
|
-
var fs = __toESM(require("node:fs/promises"), 1);
|
|
36
35
|
var import_path_utils = require("./path-utils.js");
|
|
36
|
+
var import_safe_fs = require("./safe-fs.js");
|
|
37
37
|
class PathValidator {
|
|
38
38
|
config;
|
|
39
39
|
normalizedAllowedPaths;
|
|
40
|
+
/** Canonical (symlink-resolved) forms of allowed roots, resolved once on first use. */
|
|
41
|
+
canonicalAllowedPaths = [];
|
|
42
|
+
/** Blocked paths as absolute paths, in both lexical and canonical form. */
|
|
43
|
+
resolvedBlockedPaths = [];
|
|
44
|
+
canonicalPathsReady;
|
|
40
45
|
normalizedBlockedPaths;
|
|
41
46
|
normalizedBlockedExtensions;
|
|
42
47
|
logger;
|
|
@@ -51,6 +56,7 @@ class PathValidator {
|
|
|
51
56
|
this.normalizedBlockedPaths = config.blockedPaths.map(
|
|
52
57
|
(p) => path.normalize((0, import_path_utils.expandHomeShorthand)(p))
|
|
53
58
|
);
|
|
59
|
+
this.resolvedBlockedPaths = this.resolveBlockedPaths(this.normalizedAllowedPaths);
|
|
54
60
|
this.normalizedBlockedExtensions = (config.blockedExtensions || []).map((ext) => {
|
|
55
61
|
const e = ext.startsWith(".") ? ext : `.${ext}`;
|
|
56
62
|
return e.toLowerCase();
|
|
@@ -72,8 +78,12 @@ class PathValidator {
|
|
|
72
78
|
/**
|
|
73
79
|
* Validate a file path for security and policy compliance
|
|
74
80
|
*/
|
|
75
|
-
async validatePath(filePath, operation) {
|
|
76
|
-
return this.validatePathInternal(filePath, {
|
|
81
|
+
async validatePath(filePath, operation, options = {}) {
|
|
82
|
+
return this.validatePathInternal(filePath, {
|
|
83
|
+
skipAllowedCheck: false,
|
|
84
|
+
operation,
|
|
85
|
+
followFinalSymlink: options.followFinalSymlink ?? true
|
|
86
|
+
});
|
|
77
87
|
}
|
|
78
88
|
/**
|
|
79
89
|
* Validate a file path for preview purposes.
|
|
@@ -88,7 +98,11 @@ class PathValidator {
|
|
|
88
98
|
* Used for generating UI-only previews (e.g., diffs) before the user approves directory access.
|
|
89
99
|
*/
|
|
90
100
|
async validatePathForPreview(filePath) {
|
|
91
|
-
return this.validatePathInternal(filePath, {
|
|
101
|
+
return this.validatePathInternal(filePath, {
|
|
102
|
+
skipAllowedCheck: true,
|
|
103
|
+
operation: "read",
|
|
104
|
+
followFinalSymlink: true
|
|
105
|
+
});
|
|
92
106
|
}
|
|
93
107
|
async validatePathInternal(filePath, options) {
|
|
94
108
|
if (!filePath || filePath.trim() === "") {
|
|
@@ -105,11 +119,10 @@ class PathValidator {
|
|
|
105
119
|
let normalizedPath;
|
|
106
120
|
try {
|
|
107
121
|
resolvedPath = (0, import_path_utils.resolveUserPath)(workingDir, filePath);
|
|
108
|
-
normalizedPath = resolvedPath
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
}
|
|
122
|
+
normalizedPath = await (0, import_safe_fs.canonicalizePath)(resolvedPath, {
|
|
123
|
+
followFinalSymlink: options.followFinalSymlink
|
|
124
|
+
});
|
|
125
|
+
await this.ensureCanonicalPaths();
|
|
113
126
|
} catch (error) {
|
|
114
127
|
return {
|
|
115
128
|
isValid: false,
|
|
@@ -134,7 +147,7 @@ class PathValidator {
|
|
|
134
147
|
error: `Path is not within allowed paths. Allowed: ${this.normalizedAllowedPaths.join(", ")}`
|
|
135
148
|
};
|
|
136
149
|
}
|
|
137
|
-
const blockedReason = this.isPathBlocked(normalizedPath);
|
|
150
|
+
const blockedReason = this.isPathBlocked(normalizedPath) ?? this.isPathBlocked(resolvedPath);
|
|
138
151
|
if (blockedReason) {
|
|
139
152
|
return {
|
|
140
153
|
isValid: false,
|
|
@@ -181,17 +194,31 @@ class PathValidator {
|
|
|
181
194
|
* Check if path matches blocked patterns (blacklist check)
|
|
182
195
|
*/
|
|
183
196
|
isPathBlocked(normalizedPath) {
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
const blockedFull = path.isAbsolute(blocked) ? path.normalize(blocked) : path.resolve(root, blocked);
|
|
188
|
-
if (normalizedPath === blockedFull || normalizedPath.startsWith(blockedFull + path.sep)) {
|
|
189
|
-
return `Within blocked directory: ${blocked}`;
|
|
190
|
-
}
|
|
197
|
+
for (const { blocked, fullPath } of this.resolvedBlockedPaths) {
|
|
198
|
+
if (normalizedPath === fullPath || normalizedPath.startsWith(fullPath + path.sep)) {
|
|
199
|
+
return `Within blocked directory: ${blocked}`;
|
|
191
200
|
}
|
|
192
201
|
}
|
|
193
202
|
return null;
|
|
194
203
|
}
|
|
204
|
+
/**
|
|
205
|
+
* Resolve each blocked path to an absolute path: absolute entries as-is, relative entries
|
|
206
|
+
* against each of the given roots (or the working directory when no roots are configured).
|
|
207
|
+
*/
|
|
208
|
+
resolveBlockedPaths(roots) {
|
|
209
|
+
const effectiveRoots = roots.length > 0 ? roots : [(0, import_path_utils.resolveUserPath)(process.cwd(), this.config.workingDirectory || process.cwd())];
|
|
210
|
+
const resolved = [];
|
|
211
|
+
for (const blocked of this.normalizedBlockedPaths) {
|
|
212
|
+
if (path.isAbsolute(blocked)) {
|
|
213
|
+
resolved.push({ blocked, fullPath: path.normalize(blocked) });
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
for (const root of effectiveRoots) {
|
|
217
|
+
resolved.push({ blocked, fullPath: path.resolve(root, blocked) });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return resolved;
|
|
221
|
+
}
|
|
195
222
|
/**
|
|
196
223
|
* Quick check if a path is allowed (for internal use)
|
|
197
224
|
* Note: This assumes the path is already normalized/canonicalized
|
|
@@ -207,11 +234,7 @@ class PathValidator {
|
|
|
207
234
|
if (this.normalizedAllowedPaths.length === 0) {
|
|
208
235
|
return true;
|
|
209
236
|
}
|
|
210
|
-
|
|
211
|
-
const relative = path.relative(allowedPath, normalizedPath);
|
|
212
|
-
return !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
213
|
-
});
|
|
214
|
-
if (isInConfigPaths) {
|
|
237
|
+
if (this.isInConfigAllowedPaths(normalizedPath)) {
|
|
215
238
|
return true;
|
|
216
239
|
}
|
|
217
240
|
if (this.directoryApprovalChecker) {
|
|
@@ -239,11 +262,8 @@ class PathValidator {
|
|
|
239
262
|
);
|
|
240
263
|
let normalizedPath;
|
|
241
264
|
try {
|
|
242
|
-
normalizedPath = (0, import_path_utils.resolveUserPath)(workingDir, filePath);
|
|
243
|
-
|
|
244
|
-
normalizedPath = await fs.realpath(normalizedPath);
|
|
245
|
-
} catch {
|
|
246
|
-
}
|
|
265
|
+
normalizedPath = await (0, import_safe_fs.canonicalizePath)((0, import_path_utils.resolveUserPath)(workingDir, filePath));
|
|
266
|
+
await this.ensureCanonicalPaths();
|
|
247
267
|
} catch {
|
|
248
268
|
return false;
|
|
249
269
|
}
|
|
@@ -257,10 +277,45 @@ class PathValidator {
|
|
|
257
277
|
if (this.normalizedAllowedPaths.length === 0) {
|
|
258
278
|
return true;
|
|
259
279
|
}
|
|
260
|
-
return this.normalizedAllowedPaths.some(
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
280
|
+
return [...this.normalizedAllowedPaths, ...this.canonicalAllowedPaths].some(
|
|
281
|
+
(allowedPath) => isWithinRoot(allowedPath, normalizedPath)
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Allowed roots and blocked paths are configured lexically, but validated paths are
|
|
286
|
+
* canonical. Resolve their canonical forms once, on first use, so a root reached through a
|
|
287
|
+
* symlink (for example macOS `/tmp` -> `/private/tmp`) still matches its own files and a
|
|
288
|
+
* blocked path reached through an alias is still blocked. Resolving only once means a
|
|
289
|
+
* symlink planted at a root location later cannot widen what is allowed.
|
|
290
|
+
*/
|
|
291
|
+
ensureCanonicalPaths() {
|
|
292
|
+
this.canonicalPathsReady ??= this.resolveCanonicalPaths();
|
|
293
|
+
return this.canonicalPathsReady;
|
|
294
|
+
}
|
|
295
|
+
async resolveCanonicalPaths() {
|
|
296
|
+
const canonicalize = (p) => (0, import_safe_fs.canonicalizePath)(p).catch(() => p);
|
|
297
|
+
const canonicalRoots = await Promise.all(this.normalizedAllowedPaths.map(canonicalize));
|
|
298
|
+
this.canonicalAllowedPaths = canonicalRoots.filter(
|
|
299
|
+
(canonicalPath, index) => canonicalPath !== this.normalizedAllowedPaths[index]
|
|
300
|
+
);
|
|
301
|
+
const lexicalBlocked = this.resolveBlockedPaths([
|
|
302
|
+
...this.normalizedAllowedPaths,
|
|
303
|
+
...this.canonicalAllowedPaths
|
|
304
|
+
]);
|
|
305
|
+
const canonicalBlocked = await Promise.all(
|
|
306
|
+
lexicalBlocked.map(async ({ blocked, fullPath }) => ({
|
|
307
|
+
blocked,
|
|
308
|
+
fullPath: await canonicalize(fullPath)
|
|
309
|
+
}))
|
|
310
|
+
);
|
|
311
|
+
const seen = /* @__PURE__ */ new Set();
|
|
312
|
+
this.resolvedBlockedPaths = [...lexicalBlocked, ...canonicalBlocked].filter(
|
|
313
|
+
({ fullPath }) => {
|
|
314
|
+
if (seen.has(fullPath)) return false;
|
|
315
|
+
seen.add(fullPath);
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
318
|
+
);
|
|
264
319
|
}
|
|
265
320
|
/**
|
|
266
321
|
* Get normalized allowed paths
|
|
@@ -275,6 +330,13 @@ class PathValidator {
|
|
|
275
330
|
return [...this.normalizedBlockedPaths];
|
|
276
331
|
}
|
|
277
332
|
}
|
|
333
|
+
function isWithinRoot(root, candidate) {
|
|
334
|
+
const relative = path.relative(root, candidate);
|
|
335
|
+
if (relative === "") {
|
|
336
|
+
return true;
|
|
337
|
+
}
|
|
338
|
+
return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
339
|
+
}
|
|
278
340
|
// Annotate the CommonJS export names for ESM import in node:
|
|
279
341
|
0 && (module.exports = {
|
|
280
342
|
PathValidator
|
package/dist/path-validator.d.ts
CHANGED
|
@@ -27,6 +27,11 @@ export type DirectoryApprovalChecker = (filePath: string, operation: DirectoryAp
|
|
|
27
27
|
export declare class PathValidator {
|
|
28
28
|
private config;
|
|
29
29
|
private normalizedAllowedPaths;
|
|
30
|
+
/** Canonical (symlink-resolved) forms of allowed roots, resolved once on first use. */
|
|
31
|
+
private canonicalAllowedPaths;
|
|
32
|
+
/** Blocked paths as absolute paths, in both lexical and canonical form. */
|
|
33
|
+
private resolvedBlockedPaths;
|
|
34
|
+
private canonicalPathsReady;
|
|
30
35
|
private normalizedBlockedPaths;
|
|
31
36
|
private normalizedBlockedExtensions;
|
|
32
37
|
private logger;
|
|
@@ -42,7 +47,9 @@ export declare class PathValidator {
|
|
|
42
47
|
/**
|
|
43
48
|
* Validate a file path for security and policy compliance
|
|
44
49
|
*/
|
|
45
|
-
validatePath(filePath: string, operation: DirectoryApprovalOperation
|
|
50
|
+
validatePath(filePath: string, operation: DirectoryApprovalOperation, options?: {
|
|
51
|
+
followFinalSymlink?: boolean;
|
|
52
|
+
}): Promise<PathValidation>;
|
|
46
53
|
/**
|
|
47
54
|
* Validate a file path for preview purposes.
|
|
48
55
|
*
|
|
@@ -71,6 +78,11 @@ export declare class PathValidator {
|
|
|
71
78
|
* Check if path matches blocked patterns (blacklist check)
|
|
72
79
|
*/
|
|
73
80
|
private isPathBlocked;
|
|
81
|
+
/**
|
|
82
|
+
* Resolve each blocked path to an absolute path: absolute entries as-is, relative entries
|
|
83
|
+
* against each of the given roots (or the working directory when no roots are configured).
|
|
84
|
+
*/
|
|
85
|
+
private resolveBlockedPaths;
|
|
74
86
|
/**
|
|
75
87
|
* Quick check if a path is allowed (for internal use)
|
|
76
88
|
* Note: This assumes the path is already normalized/canonicalized
|
|
@@ -97,6 +109,15 @@ export declare class PathValidator {
|
|
|
97
109
|
* Used for prompting decisions.
|
|
98
110
|
*/
|
|
99
111
|
private isInConfigAllowedPaths;
|
|
112
|
+
/**
|
|
113
|
+
* Allowed roots and blocked paths are configured lexically, but validated paths are
|
|
114
|
+
* canonical. Resolve their canonical forms once, on first use, so a root reached through a
|
|
115
|
+
* symlink (for example macOS `/tmp` -> `/private/tmp`) still matches its own files and a
|
|
116
|
+
* blocked path reached through an alias is still blocked. Resolving only once means a
|
|
117
|
+
* symlink planted at a root location later cannot widen what is allowed.
|
|
118
|
+
*/
|
|
119
|
+
private ensureCanonicalPaths;
|
|
120
|
+
private resolveCanonicalPaths;
|
|
100
121
|
/**
|
|
101
122
|
* Get normalized allowed paths
|
|
102
123
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path-validator.d.ts","sourceRoot":"","sources":["../src/path-validator.ts"],"names":[],"mappings":"AAAA;;;;GAIG;
|
|
1
|
+
{"version":3,"file":"path-validator.d.ts","sourceRoot":"","sources":["../src/path-validator.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAIjD;;;GAGG;AACH,MAAM,MAAM,0BAA0B,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AACnE,MAAM,MAAM,wBAAwB,GAAG,CACnC,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,0BAA0B,KACpC,OAAO,CAAC;AAEb;;;;;;;;;;;;GAYG;AACH,qBAAa,aAAa;IACtB,OAAO,CAAC,MAAM,CAAmB;IACjC,OAAO,CAAC,sBAAsB,CAAW;IACzC,uFAAuF;IACvF,OAAO,CAAC,qBAAqB,CAAgB;IAC7C,2EAA2E;IAC3E,OAAO,CAAC,oBAAoB,CAAoD;IAChF,OAAO,CAAC,mBAAmB,CAA4B;IACvD,OAAO,CAAC,sBAAsB,CAAW;IACzC,OAAO,CAAC,2BAA2B,CAAW;IAC9C,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,wBAAwB,CAAuC;gBAE3D,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM;IA4BpD;;;;;OAKG;IACH,2BAA2B,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI;IAKpE;;OAEG;IACG,YAAY,CACd,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,0BAA0B,EACrC,OAAO,GAAE;QAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;KAAO,GAC/C,OAAO,CAAC,cAAc,CAAC;IAQ1B;;;;;;;;;;;OAWG;IACG,sBAAsB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;YAQzD,oBAAoB;IA8FlC;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAgBxB;;;;OAIG;IACH,OAAO,CAAC,aAAa;IAIrB;;OAEG;IACH,OAAO,CAAC,aAAa;IAWrB;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAkB3B;;;OAGG;IACH,kBAAkB,CAAC,cAAc,EAAE,MAAM,EAAE,SAAS,EAAE,0BAA0B,GAAG,OAAO;IAM1F;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAqBzB;;;;;;;;;OASG;IACG,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAyB7D;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAW9B;;;;;;OAMG;IACH,OAAO,CAAC,oBAAoB;YAKd,qBAAqB;IA2BnC;;OAEG;IACH,eAAe,IAAI,MAAM,EAAE;IAI3B;;OAEG;IACH,eAAe,IAAI,MAAM,EAAE;CAG9B"}
|