-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtar.ts
More file actions
323 lines (289 loc) · 9.41 KB
/
tar.ts
File metadata and controls
323 lines (289 loc) · 9.41 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
/**
* @fileoverview Tar / tar.gz extraction with security limits and
* symlink rejection. Both functions share a `map(header)` callback
* that enforces:
*
* - max entry count (inode-exhaustion DoS guard)
* - max single-file size
* - max total extracted size
* - rejection of null bytes in entry names
* - rejection of symlink / hardlink entries
*
* The duplicate map() bodies are intentional: the surrounding state
* (entryCount, totalExtractedSize, destroyScheduled) is per-call, so
* a shared helper would require threading state through closures and
* obscure the security-defense intent.
*/
import { createReadStream } from 'node:fs'
import process from 'node:process'
import { pipeline } from 'node:stream/promises'
import { createGunzip } from 'node:zlib'
import { safeMkdir } from '../fs/safe'
import { normalizePath } from '../paths/normalize'
import { ErrorCtor } from '../primordials/error'
import {
assertArchiveExists,
DEFAULT_MAX_ENTRIES,
DEFAULT_MAX_FILE_SIZE,
DEFAULT_MAX_TOTAL_SIZE,
getTarFs,
} from './_internal'
import type { ExtractOptions } from './types'
/**
* Extract a tar archive to a directory.
*
* @param archivePath - Path to tar file
* @param outputDir - Directory to extract to
* @param options - Extraction options
*
* @example
* ```typescript
* await extractTar('/tmp/archive.tar', '/tmp/output')
* await extractTar('/tmp/archive.tar', '/tmp/output', { strip: 1 })
* ```
*/
export async function extractTar(
archivePath: string,
outputDir: string,
options: ExtractOptions = {},
): Promise<void> {
// Normalize the "missing archive" surface (see extractZip) — throw
// ENOENT up front with a clear message rather than letting the
// Node-level createReadStream eventually surface as a stream error.
assertArchiveExists(archivePath)
const {
maxEntries = DEFAULT_MAX_ENTRIES,
maxFileSize = DEFAULT_MAX_FILE_SIZE,
maxTotalSize = DEFAULT_MAX_TOTAL_SIZE,
strip = 0,
} = options
// Normalize output directory path for cross-platform compatibility
const normalizedOutputDir = normalizePath(outputDir)
await safeMkdir(normalizedOutputDir)
let totalExtractedSize = 0
let entryCount = 0
let destroyScheduled = false
const tarFs = getTarFs()
const extractStream = tarFs.extract(normalizedOutputDir, {
map: (header: { name: string; size?: number; type?: string }) => {
// Skip if destroy already scheduled
/* c8 ignore next 3 - destroyScheduled is set by the same map()
when a security limit trips; only fires after the schedule. */
if (destroyScheduled) {
return header
}
/* c8 ignore start - Security-defense branches inside tar-fs
map() schedule extractStream.destroy via process.nextTick.
tar-fs@3.1.2 has an async-cleanup race after destroy that
crashes the vitest pool runner. Re-enable once tar-fs is
upgraded or the SUT refactors destroy. */
// Check entry count to prevent inode exhaustion DoS.
entryCount += 1
if (entryCount > maxEntries) {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`Archive has too many entries: exceeded limit of ${maxEntries}`,
),
)
})
return header
}
// Reject entries with null bytes in names (defense in depth).
if (header.name.includes('\0')) {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`Invalid null byte in archive entry name: ${header.name}`,
),
)
})
return header
}
// Check for symlinks
if (header.type === 'symlink' || header.type === 'link') {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`Symlink detected in archive: ${header.name}. Symlinks are not supported for security reasons.`,
),
)
})
return header
}
// Check individual file size
if (header.size && header.size > maxFileSize) {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`File size exceeds limit: ${header.name} (${header.size} bytes > ${maxFileSize} bytes)`,
),
)
})
return header
}
// Check total extracted size
if (header.size) {
totalExtractedSize += header.size
if (totalExtractedSize > maxTotalSize) {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`Total extracted size exceeds limit: ${totalExtractedSize} bytes > ${maxTotalSize} bytes`,
),
)
})
return header
}
}
/* c8 ignore stop */
return header
},
strip,
})
// Attach error handler before starting pipeline to catch errors
extractStream.on('error', () => {
// Error will be caught by pipeline
})
const readStream = createReadStream(archivePath)
try {
await pipeline(readStream, extractStream)
} catch (e) {
// Ensure stream is cleaned up on error
readStream.destroy()
throw e
}
}
/**
* Extract a gzipped tar archive to a directory.
*
* @param archivePath - Path to tar.gz or tgz file
* @param outputDir - Directory to extract to
* @param options - Extraction options
*
* @example
* ```typescript
* await extractTarGz('/tmp/archive.tar.gz', '/tmp/output')
* await extractTarGz('/tmp/archive.tgz', '/tmp/output', { strip: 1 })
* ```
*/
export async function extractTarGz(
archivePath: string,
outputDir: string,
options: ExtractOptions = {},
): Promise<void> {
// Normalize the "missing archive" surface (see extractZip).
assertArchiveExists(archivePath)
const {
maxEntries = DEFAULT_MAX_ENTRIES,
maxFileSize = DEFAULT_MAX_FILE_SIZE,
maxTotalSize = DEFAULT_MAX_TOTAL_SIZE,
strip = 0,
} = options
// Normalize output directory path for cross-platform compatibility
const normalizedOutputDir = normalizePath(outputDir)
await safeMkdir(normalizedOutputDir)
let totalExtractedSize = 0
let entryCount = 0
let destroyScheduled = false
const tarFs = getTarFs()
const extractStream = tarFs.extract(normalizedOutputDir, {
map: (header: { name: string; size?: number; type?: string }) => {
// Skip if destroy already scheduled
/* c8 ignore next 3 - destroyScheduled is set by the same map()
when a security limit trips; only fires after the schedule. */
if (destroyScheduled) {
return header
}
/* c8 ignore start - Security-defense branches inside tar-fs
map() schedule extractStream.destroy via process.nextTick.
tar-fs@3.1.2 has an async-cleanup race after destroy that
crashes the vitest pool runner. Re-enable once tar-fs is
upgraded or the SUT refactors destroy. */
// Check entry count to prevent inode exhaustion DoS.
entryCount += 1
if (entryCount > maxEntries) {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`Archive has too many entries: exceeded limit of ${maxEntries}`,
),
)
})
return header
}
// Reject entries with null bytes in names (defense in depth).
if (header.name.includes('\0')) {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`Invalid null byte in archive entry name: ${header.name}`,
),
)
})
return header
}
// Check for symlinks
if (header.type === 'symlink' || header.type === 'link') {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`Symlink detected in archive: ${header.name}. Symlinks are not supported for security reasons.`,
),
)
})
return header
}
// Check individual file size
if (header.size && header.size > maxFileSize) {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`File size exceeds limit: ${header.name} (${header.size} bytes > ${maxFileSize} bytes)`,
),
)
})
return header
}
// Check total extracted size
if (header.size) {
totalExtractedSize += header.size
if (totalExtractedSize > maxTotalSize) {
destroyScheduled = true
process.nextTick(() => {
extractStream.destroy(
new ErrorCtor(
`Total extracted size exceeds limit: ${totalExtractedSize} bytes > ${maxTotalSize} bytes`,
),
)
})
return header
}
}
/* c8 ignore stop */
return header
},
strip,
})
// Attach error handler before starting pipeline to catch errors
extractStream.on('error', () => {
// Error will be caught by pipeline
})
const readStream = createReadStream(archivePath)
try {
await pipeline(readStream, createGunzip(), extractStream)
} catch (e) {
// Ensure stream is cleaned up on error
readStream.destroy()
throw e
}
}