-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafe.ts
More file actions
357 lines (330 loc) · 11.7 KB
/
safe.ts
File metadata and controls
357 lines (330 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
* @fileoverview Safe deletion + idempotent directory creation. The
* delete helpers gate destructive operations behind an "allowed
* directories" allow-list (temp dir, cacache dir, ~/.socket); paths
* outside those need an explicit `force: true`. The mkdir helpers
* default to `recursive: true` and swallow `EEXIST` so concurrent
* callers don't race-condition each other.
*/
import { isArray } from '../arrays/predicates'
import { isErrnoException } from '../errors/predicates'
import { getNodeFs } from '../node/fs'
import { getNodePath } from '../node/path'
import { objectFreeze } from '../objects/mutate'
import { pathLikeToString } from '../paths/normalize'
import { AtomicsWait, Int32ArrayCtor } from '../primordials/array'
import { SharedArrayBufferCtor } from '../primordials/globals'
import { StringPrototypeStartsWith } from '../primordials/string'
import { pRetry } from '../promises/retry'
import { getAllowedDirectories } from './_internal'
// Side-effect import: registers invalidatePathCache with paths/rewire
// so test-time path overrides flush the allowed-directories cache used
// by safeDelete / safeDeleteSync below. Without this import, rewiring
// the temp / cacache / socket-user dirs in a test would not affect
// subsequent safeDelete calls — they'd see stale resolved paths.
import './path-cache'
import type { MakeDirectoryOptions, PathLike } from 'node:fs'
import type {
deleteAsync as deleteAsyncType,
deleteSync as deleteSyncType,
} from '../external/del'
import type { RemoveOptions } from './types'
const defaultRemoveOptions = objectFreeze({
__proto__: null,
force: true,
maxRetries: 3,
recursive: true,
retryDelay: 200,
})
let _del:
| { deleteAsync: typeof deleteAsyncType; deleteSync: typeof deleteSyncType }
| undefined
/*@__NO_SIDE_EFFECTS__*/
export function getDel() {
if (_del === undefined) {
_del = /*@__PURE__*/ require('../external/del')
}
return _del!
}
/**
* Safely delete a file or directory asynchronously with built-in protections.
*
* Uses [`del`](https://socket.dev/npm/package/del/overview/8.0.1) for safer deletion with these safety features:
* - By default, prevents deleting the current working directory (cwd) and above
* - Allows deleting within cwd (descendant paths) without force option
* - Automatically uses force: true for temp directory, cacache, and ~/.socket subdirectories
* - Protects against accidental deletion of parent directories via `../` paths
*
* @param filepath - Path or array of paths to delete (supports glob patterns)
* @param options - Deletion options including force, retries, and recursion
* @param options.force - Set to true to allow deleting cwd and above (use with caution)
* @throws {Error} When attempting to delete protected paths without force option
*
* @example
* ```ts
* // Delete files within cwd (safe by default)
* await safeDelete('./build')
* await safeDelete('./dist')
*
* // Delete with glob patterns
* await safeDelete(['./temp/**', '!./temp/keep.txt'])
*
* // Delete with custom retry settings
* await safeDelete('./flaky-dir', { maxRetries: 5, retryDelay: 500 })
*
* // Force delete cwd or above (requires explicit force: true)
* await safeDelete('../parent-dir', { force: true })
* ```
*/
export async function safeDelete(
filepath: PathLike | PathLike[],
options?: RemoveOptions | undefined,
) {
// deleteAsync is lazily loaded via getDel()
const opts = { __proto__: null, ...options } as RemoveOptions
const patterns = isArray(filepath)
? filepath.map(pathLikeToString)
: [pathLikeToString(filepath)]
// shouldForce default is true; the allowedDirs branch fires only
// when caller passes `force: false` to bypass auto-force.
/* c8 ignore start */
let shouldForce = opts.force !== false
if (!shouldForce && patterns.length > 0) {
const path = getNodePath()
const allowedDirs = getAllowedDirectories()
const allInAllowedDirs = patterns.every(pattern => {
const resolvedPath = path.resolve(pattern)
for (const allowedDir of allowedDirs) {
const isInAllowedDir =
StringPrototypeStartsWith(resolvedPath, allowedDir + path.sep) ||
resolvedPath === allowedDir
const relativePath = path.relative(allowedDir, resolvedPath)
const isGoingBackward = StringPrototypeStartsWith(relativePath, '..')
if (isInAllowedDir && !isGoingBackward) {
return true
}
}
return false
})
if (allInAllowedDirs) {
shouldForce = true
}
}
/* c8 ignore stop */
const maxRetries = opts.maxRetries ?? defaultRemoveOptions.maxRetries
const retryDelay = opts.retryDelay ?? defaultRemoveOptions.retryDelay
/* c8 ignore start - External del call */
const del = getDel()
await pRetry(
async () => {
await del.deleteAsync(patterns, {
dryRun: false,
force: shouldForce,
onlyFiles: false,
})
},
{
retries: maxRetries,
baseDelayMs: retryDelay,
backoffFactor: 2,
signal: opts.signal,
},
)
/* c8 ignore stop */
}
/**
* Safely delete a file or directory synchronously with built-in protections.
*
* Uses [`del`](https://socket.dev/npm/package/del/overview/8.0.1) for safer deletion with these safety features:
* - By default, prevents deleting the current working directory (cwd) and above
* - Allows deleting within cwd (descendant paths) without force option
* - Automatically uses force: true for temp directory, cacache, and ~/.socket subdirectories
* - Protects against accidental deletion of parent directories via `../` paths
*
* @param filepath - Path or array of paths to delete (supports glob patterns)
* @param options - Deletion options including force, retries, and recursion
* @param options.force - Set to true to allow deleting cwd and above (use with caution)
* @throws {Error} When attempting to delete protected paths without force option
*
* @example
* ```ts
* // Delete files within cwd (safe by default)
* safeDeleteSync('./build')
* safeDeleteSync('./dist')
*
* // Delete with glob patterns
* safeDeleteSync(['./temp/**', '!./temp/keep.txt'])
*
* // Delete multiple paths
* safeDeleteSync(['./coverage', './reports'])
*
* // Force delete cwd or above (requires explicit force: true)
* safeDeleteSync('../parent-dir', { force: true })
* ```
*/
export function safeDeleteSync(
filepath: PathLike | PathLike[],
options?: RemoveOptions | undefined,
) {
// deleteSync is lazily loaded via getDel()
const opts = { __proto__: null, ...options } as RemoveOptions
const patterns = isArray(filepath)
? filepath.map(pathLikeToString)
: [pathLikeToString(filepath)]
// shouldForce default is true; the allowedDirs branch fires only
// when caller passes `force: false` to bypass auto-force.
/* c8 ignore start */
let shouldForce = opts.force !== false
if (!shouldForce && patterns.length > 0) {
const path = getNodePath()
const allowedDirs = getAllowedDirectories()
const allInAllowedDirs = patterns.every(pattern => {
const resolvedPath = path.resolve(pattern)
for (const allowedDir of allowedDirs) {
const isInAllowedDir =
StringPrototypeStartsWith(resolvedPath, allowedDir + path.sep) ||
resolvedPath === allowedDir
const relativePath = path.relative(allowedDir, resolvedPath)
const isGoingBackward = StringPrototypeStartsWith(relativePath, '..')
if (isInAllowedDir && !isGoingBackward) {
return true
}
}
return false
})
if (allInAllowedDirs) {
shouldForce = true
}
}
/* c8 ignore stop */
const maxRetries = opts.maxRetries ?? defaultRemoveOptions.maxRetries
const retryDelay = opts.retryDelay ?? defaultRemoveOptions.retryDelay
/* c8 ignore start - External del call */
const del = getDel()
let lastError: Error | undefined
let delay = retryDelay
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
del.deleteSync(patterns, {
dryRun: false,
force: shouldForce,
onlyFiles: false,
})
return
} catch (e) {
lastError = e as Error
if (attempt < maxRetries) {
// Sync sleep using Atomics.wait on a SharedArrayBuffer.
// This is a blocking wait that doesn't spin the CPU.
const waitMs = delay
AtomicsWait(
new Int32ArrayCtor(new SharedArrayBufferCtor(4)),
0,
0,
waitMs,
)
delay *= 2 // Exponential backoff
}
}
}
if (lastError) {
throw lastError
}
/* c8 ignore stop */
}
/**
* Safely create a directory asynchronously, ignoring EEXIST errors.
* This function wraps fs.promises.mkdir and handles the race condition where
* the directory might already exist, which is common in concurrent code.
*
* Unlike fs.promises.mkdir with recursive:true, this function:
* - Silently ignores EEXIST errors (directory already exists)
* - Re-throws all other errors (permissions, invalid path, etc.)
* - Works reliably in multi-process/concurrent scenarios
* - Defaults to recursive: true for convenient nested directory creation
*
* @param path - Directory path to create
* @param options - Options including recursive (default: true) and mode settings
* @returns Promise that resolves when directory is created or already exists
*
* @example
* ```ts
* // Create a directory recursively by default, no error if it exists
* await safeMkdir('./config')
*
* // Create nested directories (recursive: true is the default)
* await safeMkdir('./data/cache/temp')
*
* // Create with specific permissions
* await safeMkdir('./secure', { mode: 0o700 })
*
* // Explicitly disable recursive behavior
* await safeMkdir('./single-level', { recursive: false })
* ```
*/
export async function safeMkdir(
path: PathLike,
options?: MakeDirectoryOptions | undefined,
): Promise<void> {
const fs = getNodeFs()
const opts = { __proto__: null, recursive: true, ...options }
try {
await fs.promises.mkdir(path, opts)
// EEXIST defensive: !isErrnoException fires only on non-Error
// throws; the e.code !== 'EEXIST' arm fires only when mkdir fails
// for non-existence reasons (permissions, etc.), which tests
// don't simulate.
/* c8 ignore start */
} catch (e: unknown) {
if (!isErrnoException(e) || e.code !== 'EEXIST') {
throw e
}
}
/* c8 ignore stop */
}
/**
* Safely create a directory synchronously, ignoring EEXIST errors.
* This function wraps fs.mkdirSync and handles the race condition where
* the directory might already exist, which is common in concurrent code.
*
* Unlike fs.mkdirSync with recursive:true, this function:
* - Silently ignores EEXIST errors (directory already exists)
* - Re-throws all other errors (permissions, invalid path, etc.)
* - Works reliably in multi-process/concurrent scenarios
* - Defaults to recursive: true for convenient nested directory creation
*
* @param path - Directory path to create
* @param options - Options including recursive (default: true) and mode settings
*
* @example
* ```ts
* // Create a directory recursively by default, no error if it exists
* safeMkdirSync('./config')
*
* // Create nested directories (recursive: true is the default)
* safeMkdirSync('./data/cache/temp')
*
* // Create with specific permissions
* safeMkdirSync('./secure', { mode: 0o700 })
*
* // Explicitly disable recursive behavior
* safeMkdirSync('./single-level', { recursive: false })
* ```
*/
export function safeMkdirSync(
path: PathLike,
options?: MakeDirectoryOptions | undefined,
): void {
const fs = getNodeFs()
const opts = { __proto__: null, recursive: true, ...options }
try {
fs.mkdirSync(path, opts)
// EEXIST defensive (see safeMkdir).
/* c8 ignore start */
} catch (e: unknown) {
if (!isErrnoException(e) || e.code !== 'EEXIST') {
throw e
}
}
/* c8 ignore stop */
}