@dexto/tools-filesystem 1.15.0-beta.2 → 1.15.0-beta.4
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 +4 -4
package/dist/path-validator.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import * as path from "node:path";
|
|
2
|
-
import * as fs from "node:fs/promises";
|
|
3
2
|
import { expandHomeShorthand, resolveUserPath } from "./path-utils.js";
|
|
3
|
+
import { canonicalizePath } from "./safe-fs.js";
|
|
4
4
|
class PathValidator {
|
|
5
5
|
config;
|
|
6
6
|
normalizedAllowedPaths;
|
|
7
|
+
/** Canonical (symlink-resolved) forms of allowed roots, resolved once on first use. */
|
|
8
|
+
canonicalAllowedPaths = [];
|
|
9
|
+
/** Blocked paths as absolute paths, in both lexical and canonical form. */
|
|
10
|
+
resolvedBlockedPaths = [];
|
|
11
|
+
canonicalPathsReady;
|
|
7
12
|
normalizedBlockedPaths;
|
|
8
13
|
normalizedBlockedExtensions;
|
|
9
14
|
logger;
|
|
@@ -18,6 +23,7 @@ class PathValidator {
|
|
|
18
23
|
this.normalizedBlockedPaths = config.blockedPaths.map(
|
|
19
24
|
(p) => path.normalize(expandHomeShorthand(p))
|
|
20
25
|
);
|
|
26
|
+
this.resolvedBlockedPaths = this.resolveBlockedPaths(this.normalizedAllowedPaths);
|
|
21
27
|
this.normalizedBlockedExtensions = (config.blockedExtensions || []).map((ext) => {
|
|
22
28
|
const e = ext.startsWith(".") ? ext : `.${ext}`;
|
|
23
29
|
return e.toLowerCase();
|
|
@@ -39,8 +45,12 @@ class PathValidator {
|
|
|
39
45
|
/**
|
|
40
46
|
* Validate a file path for security and policy compliance
|
|
41
47
|
*/
|
|
42
|
-
async validatePath(filePath, operation) {
|
|
43
|
-
return this.validatePathInternal(filePath, {
|
|
48
|
+
async validatePath(filePath, operation, options = {}) {
|
|
49
|
+
return this.validatePathInternal(filePath, {
|
|
50
|
+
skipAllowedCheck: false,
|
|
51
|
+
operation,
|
|
52
|
+
followFinalSymlink: options.followFinalSymlink ?? true
|
|
53
|
+
});
|
|
44
54
|
}
|
|
45
55
|
/**
|
|
46
56
|
* Validate a file path for preview purposes.
|
|
@@ -55,7 +65,11 @@ class PathValidator {
|
|
|
55
65
|
* Used for generating UI-only previews (e.g., diffs) before the user approves directory access.
|
|
56
66
|
*/
|
|
57
67
|
async validatePathForPreview(filePath) {
|
|
58
|
-
return this.validatePathInternal(filePath, {
|
|
68
|
+
return this.validatePathInternal(filePath, {
|
|
69
|
+
skipAllowedCheck: true,
|
|
70
|
+
operation: "read",
|
|
71
|
+
followFinalSymlink: true
|
|
72
|
+
});
|
|
59
73
|
}
|
|
60
74
|
async validatePathInternal(filePath, options) {
|
|
61
75
|
if (!filePath || filePath.trim() === "") {
|
|
@@ -72,11 +86,10 @@ class PathValidator {
|
|
|
72
86
|
let normalizedPath;
|
|
73
87
|
try {
|
|
74
88
|
resolvedPath = resolveUserPath(workingDir, filePath);
|
|
75
|
-
normalizedPath = resolvedPath
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
}
|
|
89
|
+
normalizedPath = await canonicalizePath(resolvedPath, {
|
|
90
|
+
followFinalSymlink: options.followFinalSymlink
|
|
91
|
+
});
|
|
92
|
+
await this.ensureCanonicalPaths();
|
|
80
93
|
} catch (error) {
|
|
81
94
|
return {
|
|
82
95
|
isValid: false,
|
|
@@ -101,7 +114,7 @@ class PathValidator {
|
|
|
101
114
|
error: `Path is not within allowed paths. Allowed: ${this.normalizedAllowedPaths.join(", ")}`
|
|
102
115
|
};
|
|
103
116
|
}
|
|
104
|
-
const blockedReason = this.isPathBlocked(normalizedPath);
|
|
117
|
+
const blockedReason = this.isPathBlocked(normalizedPath) ?? this.isPathBlocked(resolvedPath);
|
|
105
118
|
if (blockedReason) {
|
|
106
119
|
return {
|
|
107
120
|
isValid: false,
|
|
@@ -148,17 +161,31 @@ class PathValidator {
|
|
|
148
161
|
* Check if path matches blocked patterns (blacklist check)
|
|
149
162
|
*/
|
|
150
163
|
isPathBlocked(normalizedPath) {
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const blockedFull = path.isAbsolute(blocked) ? path.normalize(blocked) : path.resolve(root, blocked);
|
|
155
|
-
if (normalizedPath === blockedFull || normalizedPath.startsWith(blockedFull + path.sep)) {
|
|
156
|
-
return `Within blocked directory: ${blocked}`;
|
|
157
|
-
}
|
|
164
|
+
for (const { blocked, fullPath } of this.resolvedBlockedPaths) {
|
|
165
|
+
if (normalizedPath === fullPath || normalizedPath.startsWith(fullPath + path.sep)) {
|
|
166
|
+
return `Within blocked directory: ${blocked}`;
|
|
158
167
|
}
|
|
159
168
|
}
|
|
160
169
|
return null;
|
|
161
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* Resolve each blocked path to an absolute path: absolute entries as-is, relative entries
|
|
173
|
+
* against each of the given roots (or the working directory when no roots are configured).
|
|
174
|
+
*/
|
|
175
|
+
resolveBlockedPaths(roots) {
|
|
176
|
+
const effectiveRoots = roots.length > 0 ? roots : [resolveUserPath(process.cwd(), this.config.workingDirectory || process.cwd())];
|
|
177
|
+
const resolved = [];
|
|
178
|
+
for (const blocked of this.normalizedBlockedPaths) {
|
|
179
|
+
if (path.isAbsolute(blocked)) {
|
|
180
|
+
resolved.push({ blocked, fullPath: path.normalize(blocked) });
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
for (const root of effectiveRoots) {
|
|
184
|
+
resolved.push({ blocked, fullPath: path.resolve(root, blocked) });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return resolved;
|
|
188
|
+
}
|
|
162
189
|
/**
|
|
163
190
|
* Quick check if a path is allowed (for internal use)
|
|
164
191
|
* Note: This assumes the path is already normalized/canonicalized
|
|
@@ -174,11 +201,7 @@ class PathValidator {
|
|
|
174
201
|
if (this.normalizedAllowedPaths.length === 0) {
|
|
175
202
|
return true;
|
|
176
203
|
}
|
|
177
|
-
|
|
178
|
-
const relative = path.relative(allowedPath, normalizedPath);
|
|
179
|
-
return !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
180
|
-
});
|
|
181
|
-
if (isInConfigPaths) {
|
|
204
|
+
if (this.isInConfigAllowedPaths(normalizedPath)) {
|
|
182
205
|
return true;
|
|
183
206
|
}
|
|
184
207
|
if (this.directoryApprovalChecker) {
|
|
@@ -206,11 +229,8 @@ class PathValidator {
|
|
|
206
229
|
);
|
|
207
230
|
let normalizedPath;
|
|
208
231
|
try {
|
|
209
|
-
normalizedPath = resolveUserPath(workingDir, filePath);
|
|
210
|
-
|
|
211
|
-
normalizedPath = await fs.realpath(normalizedPath);
|
|
212
|
-
} catch {
|
|
213
|
-
}
|
|
232
|
+
normalizedPath = await canonicalizePath(resolveUserPath(workingDir, filePath));
|
|
233
|
+
await this.ensureCanonicalPaths();
|
|
214
234
|
} catch {
|
|
215
235
|
return false;
|
|
216
236
|
}
|
|
@@ -224,10 +244,45 @@ class PathValidator {
|
|
|
224
244
|
if (this.normalizedAllowedPaths.length === 0) {
|
|
225
245
|
return true;
|
|
226
246
|
}
|
|
227
|
-
return this.normalizedAllowedPaths.some(
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
247
|
+
return [...this.normalizedAllowedPaths, ...this.canonicalAllowedPaths].some(
|
|
248
|
+
(allowedPath) => isWithinRoot(allowedPath, normalizedPath)
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Allowed roots and blocked paths are configured lexically, but validated paths are
|
|
253
|
+
* canonical. Resolve their canonical forms once, on first use, so a root reached through a
|
|
254
|
+
* symlink (for example macOS `/tmp` -> `/private/tmp`) still matches its own files and a
|
|
255
|
+
* blocked path reached through an alias is still blocked. Resolving only once means a
|
|
256
|
+
* symlink planted at a root location later cannot widen what is allowed.
|
|
257
|
+
*/
|
|
258
|
+
ensureCanonicalPaths() {
|
|
259
|
+
this.canonicalPathsReady ??= this.resolveCanonicalPaths();
|
|
260
|
+
return this.canonicalPathsReady;
|
|
261
|
+
}
|
|
262
|
+
async resolveCanonicalPaths() {
|
|
263
|
+
const canonicalize = (p) => canonicalizePath(p).catch(() => p);
|
|
264
|
+
const canonicalRoots = await Promise.all(this.normalizedAllowedPaths.map(canonicalize));
|
|
265
|
+
this.canonicalAllowedPaths = canonicalRoots.filter(
|
|
266
|
+
(canonicalPath, index) => canonicalPath !== this.normalizedAllowedPaths[index]
|
|
267
|
+
);
|
|
268
|
+
const lexicalBlocked = this.resolveBlockedPaths([
|
|
269
|
+
...this.normalizedAllowedPaths,
|
|
270
|
+
...this.canonicalAllowedPaths
|
|
271
|
+
]);
|
|
272
|
+
const canonicalBlocked = await Promise.all(
|
|
273
|
+
lexicalBlocked.map(async ({ blocked, fullPath }) => ({
|
|
274
|
+
blocked,
|
|
275
|
+
fullPath: await canonicalize(fullPath)
|
|
276
|
+
}))
|
|
277
|
+
);
|
|
278
|
+
const seen = /* @__PURE__ */ new Set();
|
|
279
|
+
this.resolvedBlockedPaths = [...lexicalBlocked, ...canonicalBlocked].filter(
|
|
280
|
+
({ fullPath }) => {
|
|
281
|
+
if (seen.has(fullPath)) return false;
|
|
282
|
+
seen.add(fullPath);
|
|
283
|
+
return true;
|
|
284
|
+
}
|
|
285
|
+
);
|
|
231
286
|
}
|
|
232
287
|
/**
|
|
233
288
|
* Get normalized allowed paths
|
|
@@ -242,6 +297,13 @@ class PathValidator {
|
|
|
242
297
|
return [...this.normalizedBlockedPaths];
|
|
243
298
|
}
|
|
244
299
|
}
|
|
300
|
+
function isWithinRoot(root, candidate) {
|
|
301
|
+
const relative = path.relative(root, candidate);
|
|
302
|
+
if (relative === "") {
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
306
|
+
}
|
|
245
307
|
export {
|
|
246
308
|
PathValidator
|
|
247
309
|
};
|
package/dist/safe-fs.cjs
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
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 safe_fs_exports = {};
|
|
30
|
+
__export(safe_fs_exports, {
|
|
31
|
+
canonicalizePath: () => canonicalizePath,
|
|
32
|
+
mkdirNoFollow: () => mkdirNoFollow,
|
|
33
|
+
writeFileNoFollow: () => writeFileNoFollow
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(safe_fs_exports);
|
|
36
|
+
var import_node_fs = require("node:fs");
|
|
37
|
+
var fs = __toESM(require("node:fs/promises"), 1);
|
|
38
|
+
var path = __toESM(require("node:path"), 1);
|
|
39
|
+
const MAX_SYMLINK_FOLLOWS = 40;
|
|
40
|
+
function errorCode(error) {
|
|
41
|
+
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : void 0;
|
|
42
|
+
}
|
|
43
|
+
function fsError(code, message) {
|
|
44
|
+
const error = new Error(message);
|
|
45
|
+
error.code = code;
|
|
46
|
+
return error;
|
|
47
|
+
}
|
|
48
|
+
async function canonicalizePath(targetPath, options = {}) {
|
|
49
|
+
const absolute = path.resolve(targetPath);
|
|
50
|
+
if (options.followFinalSymlink === false) {
|
|
51
|
+
const parent = path.dirname(absolute);
|
|
52
|
+
if (parent === absolute) {
|
|
53
|
+
return absolute;
|
|
54
|
+
}
|
|
55
|
+
const canonicalParent = await canonicalizeInternal(parent, { follows: 0 });
|
|
56
|
+
return path.join(canonicalParent, path.basename(absolute));
|
|
57
|
+
}
|
|
58
|
+
return canonicalizeInternal(absolute, { follows: 0 });
|
|
59
|
+
}
|
|
60
|
+
async function canonicalizeInternal(targetPath, budget) {
|
|
61
|
+
try {
|
|
62
|
+
return await fs.realpath(targetPath);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (errorCode(error) === "ELOOP") {
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const parent = path.dirname(targetPath);
|
|
69
|
+
if (parent === targetPath) {
|
|
70
|
+
return targetPath;
|
|
71
|
+
}
|
|
72
|
+
const canonicalParent = await canonicalizeInternal(parent, budget);
|
|
73
|
+
const candidate = path.join(canonicalParent, path.basename(targetPath));
|
|
74
|
+
let stats;
|
|
75
|
+
try {
|
|
76
|
+
stats = await fs.lstat(candidate);
|
|
77
|
+
} catch {
|
|
78
|
+
stats = void 0;
|
|
79
|
+
}
|
|
80
|
+
if (stats?.isSymbolicLink()) {
|
|
81
|
+
budget.follows += 1;
|
|
82
|
+
if (budget.follows > MAX_SYMLINK_FOLLOWS) {
|
|
83
|
+
throw fsError("ELOOP", `Too many levels of symbolic links: ${targetPath}`);
|
|
84
|
+
}
|
|
85
|
+
const linkTarget = await fs.readlink(candidate);
|
|
86
|
+
return canonicalizeInternal(path.resolve(canonicalParent, linkTarget), budget);
|
|
87
|
+
}
|
|
88
|
+
return candidate;
|
|
89
|
+
}
|
|
90
|
+
async function mkdirNoFollow(canonicalDir) {
|
|
91
|
+
const parts = [];
|
|
92
|
+
let current = path.resolve(canonicalDir);
|
|
93
|
+
while (path.dirname(current) !== current) {
|
|
94
|
+
parts.unshift(current);
|
|
95
|
+
current = path.dirname(current);
|
|
96
|
+
}
|
|
97
|
+
let created = false;
|
|
98
|
+
for (const part of parts) {
|
|
99
|
+
let stats;
|
|
100
|
+
try {
|
|
101
|
+
stats = await fs.lstat(part);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (errorCode(error) !== "ENOENT") {
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (!stats) {
|
|
108
|
+
try {
|
|
109
|
+
await fs.mkdir(part);
|
|
110
|
+
created = true;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (errorCode(error) !== "EEXIST") {
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
stats = await fs.lstat(part);
|
|
117
|
+
}
|
|
118
|
+
if (stats.isSymbolicLink()) {
|
|
119
|
+
throw fsError("ELOOP", `Path changed during operation (symlink at ${part})`);
|
|
120
|
+
}
|
|
121
|
+
if (!stats.isDirectory()) {
|
|
122
|
+
throw fsError("ENOTDIR", `Not a directory: ${part}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return created;
|
|
126
|
+
}
|
|
127
|
+
const O_NOFOLLOW = import_node_fs.constants.O_NOFOLLOW ?? 0;
|
|
128
|
+
async function openForWrite(canonicalPath) {
|
|
129
|
+
try {
|
|
130
|
+
const handle2 = await fs.open(
|
|
131
|
+
canonicalPath,
|
|
132
|
+
import_node_fs.constants.O_WRONLY | import_node_fs.constants.O_CREAT | import_node_fs.constants.O_EXCL | O_NOFOLLOW,
|
|
133
|
+
438
|
|
134
|
+
);
|
|
135
|
+
return { handle: handle2, created: true };
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (errorCode(error) !== "EEXIST") {
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const handle = await fs.open(canonicalPath, import_node_fs.constants.O_WRONLY | O_NOFOLLOW);
|
|
142
|
+
return { handle, created: false };
|
|
143
|
+
}
|
|
144
|
+
async function writeFileNoFollow(canonicalPath, content, encoding, isAllowed) {
|
|
145
|
+
await mkdirNoFollow(path.dirname(canonicalPath));
|
|
146
|
+
const { handle, created } = await openForWrite(canonicalPath);
|
|
147
|
+
let verified = false;
|
|
148
|
+
let openedIno;
|
|
149
|
+
try {
|
|
150
|
+
const openedStats = await handle.stat();
|
|
151
|
+
openedIno = { dev: openedStats.dev, ino: openedStats.ino };
|
|
152
|
+
const recheckedPath = await canonicalizePath(canonicalPath);
|
|
153
|
+
const pathStats = await fs.lstat(recheckedPath);
|
|
154
|
+
if (recheckedPath !== canonicalPath || !isAllowed(recheckedPath) || !pathStats.isFile() || pathStats.dev !== openedStats.dev || pathStats.ino !== openedStats.ino) {
|
|
155
|
+
throw fsError(
|
|
156
|
+
"EPERM",
|
|
157
|
+
`Path changed during write and now resolves elsewhere: ${canonicalPath}`
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
verified = true;
|
|
161
|
+
await handle.truncate(0);
|
|
162
|
+
await handle.writeFile(content, { encoding });
|
|
163
|
+
} finally {
|
|
164
|
+
await handle.close();
|
|
165
|
+
if (!verified && created && openedIno) {
|
|
166
|
+
await removeCreatedFile(canonicalPath, openedIno);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async function removeCreatedFile(canonicalPath, opened) {
|
|
171
|
+
try {
|
|
172
|
+
const stats = await fs.stat(canonicalPath);
|
|
173
|
+
if (stats.dev === opened.dev && stats.ino === opened.ino && stats.size === 0) {
|
|
174
|
+
await fs.unlink(canonicalPath);
|
|
175
|
+
}
|
|
176
|
+
} catch {
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
180
|
+
0 && (module.exports = {
|
|
181
|
+
canonicalizePath,
|
|
182
|
+
mkdirNoFollow,
|
|
183
|
+
writeFileNoFollow
|
|
184
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Symlink-safe filesystem helpers.
|
|
3
|
+
*
|
|
4
|
+
* `fs.realpath` only works for paths that already exist. For paths that do not exist yet
|
|
5
|
+
* (new files, new directories) we canonicalize the nearest existing ancestor and resolve
|
|
6
|
+
* dangling symlinks ourselves, so policy checks always see where a write will really land.
|
|
7
|
+
*/
|
|
8
|
+
import type { BufferEncoding } from './types.js';
|
|
9
|
+
export type CanonicalizeOptions = {
|
|
10
|
+
/**
|
|
11
|
+
* When false, a symlink in the final component is not followed: the result is the canonical
|
|
12
|
+
* parent joined with the link's own name. Use this for operations that act on the link
|
|
13
|
+
* itself (delete, rename source).
|
|
14
|
+
*/
|
|
15
|
+
followFinalSymlink?: boolean;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Resolve an absolute path to its canonical form, following every symlink that exists on disk,
|
|
19
|
+
* including a dangling symlink in the final component. Missing trailing components are appended
|
|
20
|
+
* to the canonical form of their nearest existing ancestor.
|
|
21
|
+
*
|
|
22
|
+
* Throws ELOOP when more than {@link MAX_SYMLINK_FOLLOWS} symlinks have to be followed.
|
|
23
|
+
*/
|
|
24
|
+
export declare function canonicalizePath(targetPath: string, options?: CanonicalizeOptions): Promise<string>;
|
|
25
|
+
/**
|
|
26
|
+
* Create `canonicalDir` and any missing ancestors one level at a time, refusing to traverse a
|
|
27
|
+
* symlink. `canonicalDir` must already be canonical, so any symlink met on the way was swapped
|
|
28
|
+
* in after validation.
|
|
29
|
+
*/
|
|
30
|
+
export declare function mkdirNoFollow(canonicalDir: string): Promise<boolean>;
|
|
31
|
+
/**
|
|
32
|
+
* Write a file at an already-validated canonical path without following symlinks.
|
|
33
|
+
*
|
|
34
|
+
* - Missing parent directories are created one level at a time without following symlinks.
|
|
35
|
+
* - The final component is opened with O_NOFOLLOW, so a symlink swapped in after validation
|
|
36
|
+
* makes the open fail instead of writing through it.
|
|
37
|
+
* - After opening, the path is canonicalized again and the opened inode is compared with the
|
|
38
|
+
* inode at that path. If any directory component changed into a symlink, or the canonical
|
|
39
|
+
* path is no longer accepted by `isAllowed`, nothing is written (a file this call created is
|
|
40
|
+
* removed again).
|
|
41
|
+
* - The file is truncated only after these checks pass, so existing files are never clobbered
|
|
42
|
+
* through a redirected path.
|
|
43
|
+
*/
|
|
44
|
+
export declare function writeFileNoFollow(canonicalPath: string, content: string, encoding: BufferEncoding, isAllowed: (canonicalPath: string) => boolean): Promise<void>;
|
|
45
|
+
//# sourceMappingURL=safe-fs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"safe-fs.d.ts","sourceRoot":"","sources":["../src/safe-fs.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAiBjD,MAAM,MAAM,mBAAmB,GAAG;IAC9B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAEF;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CAClC,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE,mBAAwB,GAClC,OAAO,CAAC,MAAM,CAAC,CAWjB;AA2CD;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAuC1E;AAuBD;;;;;;;;;;;;GAYG;AACH,wBAAsB,iBAAiB,CACnC,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,cAAc,EACxB,SAAS,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,OAAO,GAC9C,OAAO,CAAC,IAAI,CAAC,CAkCf"}
|
package/dist/safe-fs.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { constants as fsConstants } from "node:fs";
|
|
2
|
+
import * as fs from "node:fs/promises";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
const MAX_SYMLINK_FOLLOWS = 40;
|
|
5
|
+
function errorCode(error) {
|
|
6
|
+
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : void 0;
|
|
7
|
+
}
|
|
8
|
+
function fsError(code, message) {
|
|
9
|
+
const error = new Error(message);
|
|
10
|
+
error.code = code;
|
|
11
|
+
return error;
|
|
12
|
+
}
|
|
13
|
+
async function canonicalizePath(targetPath, options = {}) {
|
|
14
|
+
const absolute = path.resolve(targetPath);
|
|
15
|
+
if (options.followFinalSymlink === false) {
|
|
16
|
+
const parent = path.dirname(absolute);
|
|
17
|
+
if (parent === absolute) {
|
|
18
|
+
return absolute;
|
|
19
|
+
}
|
|
20
|
+
const canonicalParent = await canonicalizeInternal(parent, { follows: 0 });
|
|
21
|
+
return path.join(canonicalParent, path.basename(absolute));
|
|
22
|
+
}
|
|
23
|
+
return canonicalizeInternal(absolute, { follows: 0 });
|
|
24
|
+
}
|
|
25
|
+
async function canonicalizeInternal(targetPath, budget) {
|
|
26
|
+
try {
|
|
27
|
+
return await fs.realpath(targetPath);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (errorCode(error) === "ELOOP") {
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const parent = path.dirname(targetPath);
|
|
34
|
+
if (parent === targetPath) {
|
|
35
|
+
return targetPath;
|
|
36
|
+
}
|
|
37
|
+
const canonicalParent = await canonicalizeInternal(parent, budget);
|
|
38
|
+
const candidate = path.join(canonicalParent, path.basename(targetPath));
|
|
39
|
+
let stats;
|
|
40
|
+
try {
|
|
41
|
+
stats = await fs.lstat(candidate);
|
|
42
|
+
} catch {
|
|
43
|
+
stats = void 0;
|
|
44
|
+
}
|
|
45
|
+
if (stats?.isSymbolicLink()) {
|
|
46
|
+
budget.follows += 1;
|
|
47
|
+
if (budget.follows > MAX_SYMLINK_FOLLOWS) {
|
|
48
|
+
throw fsError("ELOOP", `Too many levels of symbolic links: ${targetPath}`);
|
|
49
|
+
}
|
|
50
|
+
const linkTarget = await fs.readlink(candidate);
|
|
51
|
+
return canonicalizeInternal(path.resolve(canonicalParent, linkTarget), budget);
|
|
52
|
+
}
|
|
53
|
+
return candidate;
|
|
54
|
+
}
|
|
55
|
+
async function mkdirNoFollow(canonicalDir) {
|
|
56
|
+
const parts = [];
|
|
57
|
+
let current = path.resolve(canonicalDir);
|
|
58
|
+
while (path.dirname(current) !== current) {
|
|
59
|
+
parts.unshift(current);
|
|
60
|
+
current = path.dirname(current);
|
|
61
|
+
}
|
|
62
|
+
let created = false;
|
|
63
|
+
for (const part of parts) {
|
|
64
|
+
let stats;
|
|
65
|
+
try {
|
|
66
|
+
stats = await fs.lstat(part);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (errorCode(error) !== "ENOENT") {
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (!stats) {
|
|
73
|
+
try {
|
|
74
|
+
await fs.mkdir(part);
|
|
75
|
+
created = true;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (errorCode(error) !== "EEXIST") {
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
stats = await fs.lstat(part);
|
|
82
|
+
}
|
|
83
|
+
if (stats.isSymbolicLink()) {
|
|
84
|
+
throw fsError("ELOOP", `Path changed during operation (symlink at ${part})`);
|
|
85
|
+
}
|
|
86
|
+
if (!stats.isDirectory()) {
|
|
87
|
+
throw fsError("ENOTDIR", `Not a directory: ${part}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return created;
|
|
91
|
+
}
|
|
92
|
+
const O_NOFOLLOW = fsConstants.O_NOFOLLOW ?? 0;
|
|
93
|
+
async function openForWrite(canonicalPath) {
|
|
94
|
+
try {
|
|
95
|
+
const handle2 = await fs.open(
|
|
96
|
+
canonicalPath,
|
|
97
|
+
fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | O_NOFOLLOW,
|
|
98
|
+
438
|
|
99
|
+
);
|
|
100
|
+
return { handle: handle2, created: true };
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (errorCode(error) !== "EEXIST") {
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const handle = await fs.open(canonicalPath, fsConstants.O_WRONLY | O_NOFOLLOW);
|
|
107
|
+
return { handle, created: false };
|
|
108
|
+
}
|
|
109
|
+
async function writeFileNoFollow(canonicalPath, content, encoding, isAllowed) {
|
|
110
|
+
await mkdirNoFollow(path.dirname(canonicalPath));
|
|
111
|
+
const { handle, created } = await openForWrite(canonicalPath);
|
|
112
|
+
let verified = false;
|
|
113
|
+
let openedIno;
|
|
114
|
+
try {
|
|
115
|
+
const openedStats = await handle.stat();
|
|
116
|
+
openedIno = { dev: openedStats.dev, ino: openedStats.ino };
|
|
117
|
+
const recheckedPath = await canonicalizePath(canonicalPath);
|
|
118
|
+
const pathStats = await fs.lstat(recheckedPath);
|
|
119
|
+
if (recheckedPath !== canonicalPath || !isAllowed(recheckedPath) || !pathStats.isFile() || pathStats.dev !== openedStats.dev || pathStats.ino !== openedStats.ino) {
|
|
120
|
+
throw fsError(
|
|
121
|
+
"EPERM",
|
|
122
|
+
`Path changed during write and now resolves elsewhere: ${canonicalPath}`
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
verified = true;
|
|
126
|
+
await handle.truncate(0);
|
|
127
|
+
await handle.writeFile(content, { encoding });
|
|
128
|
+
} finally {
|
|
129
|
+
await handle.close();
|
|
130
|
+
if (!verified && created && openedIno) {
|
|
131
|
+
await removeCreatedFile(canonicalPath, openedIno);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async function removeCreatedFile(canonicalPath, opened) {
|
|
136
|
+
try {
|
|
137
|
+
const stats = await fs.stat(canonicalPath);
|
|
138
|
+
if (stats.dev === opened.dev && stats.ino === opened.ino && stats.size === 0) {
|
|
139
|
+
await fs.unlink(canonicalPath);
|
|
140
|
+
}
|
|
141
|
+
} catch {
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export {
|
|
145
|
+
canonicalizePath,
|
|
146
|
+
mkdirNoFollow,
|
|
147
|
+
writeFileNoFollow
|
|
148
|
+
};
|