@vltpkg/tar 1.0.2 → 1.0.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/README.md CHANGED
@@ -83,6 +83,14 @@ by default (with the same windows/umask caveats as files, so maybe
83
83
  that's `0o775` or some such.) All ctime/mtime/atime/birthtime values
84
84
  will just be left as the current time.
85
85
 
86
+ Gzip-compressed tarballs are inflated with a size bound before any tar
87
+ structure checks run. The cap is the smaller of 2 GiB and 1000 times
88
+ the compressed size (the same 1000:1 ratio node-tar and npm use).
89
+ Exceeding it fails with `tarball exceeds maximum unpacked size` rather
90
+ than allocating the decompressed buffer. Raise the ceiling with
91
+ `VLT_TAR_MAX_UNPACKED_BYTES` if a legitimate package is larger than 2
92
+ GiB unpacked.
93
+
86
94
  It does not do any of the binary linking or other stuff that a package
87
95
  manager will need to do. It _just_ does the unpack, as ruthlessly fast
88
96
  as possible, and that's all.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export * from './unpack.ts';
1
+ export { unpack } from './unpack.ts';
2
2
  export * from './pool.ts';
3
3
  export * from './unpack-request.ts';
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- export * from "./unpack.js";
1
+ export { unpack } from "./unpack.js";
2
2
  export * from "./pool.js";
3
3
  export * from "./unpack-request.js";
package/dist/unpack.d.ts CHANGED
@@ -1 +1,6 @@
1
+ export declare const checkFs: (h: {
2
+ path?: string;
3
+ }, tarDir: string | undefined, target: string) => h is {
4
+ path: string;
5
+ };
1
6
  export declare const unpack: (tarData: Buffer, target: string) => Promise<void>;
package/dist/unpack.js CHANGED
@@ -7,9 +7,34 @@ import { Header } from 'tar/header';
7
7
  import { Pax } from 'tar/pax';
8
8
  import { unzip as unzipCB } from 'node:zlib';
9
9
  import { findTarDir } from "./find-tar-dir.js";
10
- const unzip = async (input) => new Promise((res, rej) =>
11
- /* c8 ignore start */
12
- unzipCB(input, (er, result) => (er ? rej(er) : res(result))));
10
+ // Matches node-tar's MAX_DECOMPRESSION_RATIO, which npm uses via pacote.
11
+ const MAX_DECOMPRESSION_RATIO = 1000;
12
+ // node-tar streams, so its ratio alone bounds peak memory. We inflate into
13
+ // a single Buffer, so without a ceiling a large tarball still commits
14
+ // ratio * compressed bytes.
15
+ const defaultMaxUnpackedBytes = 2 * 1024 * 1024 * 1024;
16
+ const parseMaxUnpackedBytes = (raw) => {
17
+ const n = Number(raw);
18
+ return Number.isFinite(n) && n >= 1 ?
19
+ Math.floor(n)
20
+ : defaultMaxUnpackedBytes;
21
+ };
22
+ const maxUnpackedBytes = parseMaxUnpackedBytes(process.env.VLT_TAR_MAX_UNPACKED_BYTES);
23
+ const unzip = async (input) => {
24
+ const max = Math.min(maxUnpackedBytes, input.length * MAX_DECOMPRESSION_RATIO);
25
+ return new Promise((res, rej) => unzipCB(input, { maxOutputLength: max }, (er, result) => {
26
+ if (!er)
27
+ return res(result);
28
+ return rej((er.code ===
29
+ 'ERR_BUFFER_TOO_LARGE') ?
30
+ error('tarball exceeds maximum unpacked size', {
31
+ found: input.length,
32
+ max,
33
+ cause: er,
34
+ })
35
+ : er);
36
+ }));
37
+ };
13
38
  const exists = async (path) => {
14
39
  try {
15
40
  await lstat(path);
@@ -22,27 +47,115 @@ const exists = async (path) => {
22
47
  let id = 1;
23
48
  const tmp = randomBytes(6).toString('hex') + '.';
24
49
  const tmpSuffix = () => tmp + String(id++);
25
- const checkFs = (h, tarDir, target) => {
26
- /* c8 ignore start - impossible */
50
+ /* c8 ignore start - case-folding is platform-specific */
51
+ const foldKeys = process.platform === 'darwin' || process.platform === 'win32';
52
+ const entryKey = (p) => (foldKeys ? p.toLowerCase() : p);
53
+ /* c8 ignore stop */
54
+ // Shared across concurrent unpacks. Reify runs many extractions at
55
+ // once; a per-tarball pool would multiply in-flight writeFile fds.
56
+ const parseWriteLanes = (raw) => {
57
+ const n = Number(raw);
58
+ return Number.isFinite(n) && n >= 1 ? Math.floor(n) : 64;
59
+ };
60
+ const writeLaneLimit = parseWriteLanes(process.env.VLT_TAR_WRITE_LANES);
61
+ let writeLanesUsed = 0;
62
+ const writeLaneWaiters = [];
63
+ let writeLaneHead = 0;
64
+ const acquireWriteLane = async () => {
65
+ if (writeLanesUsed < writeLaneLimit) {
66
+ writeLanesUsed++;
67
+ return;
68
+ }
69
+ await new Promise(res => writeLaneWaiters.push(res));
70
+ };
71
+ const releaseWriteLane = () => {
72
+ // consume from a head index instead of shift(): shift is O(n) per
73
+ // release, quadratic when many writes queue behind the lane limit.
74
+ const next = writeLaneWaiters[writeLaneHead];
75
+ if (next) {
76
+ writeLaneWaiters[writeLaneHead] = undefined;
77
+ writeLaneHead++;
78
+ if (writeLaneHead === writeLaneWaiters.length) {
79
+ writeLaneWaiters.length = 0;
80
+ writeLaneHead = 0;
81
+ }
82
+ next();
83
+ }
84
+ else {
85
+ writeLanesUsed--;
86
+ }
87
+ };
88
+ const withWriteLane = async (fn) => {
89
+ await acquireWriteLane();
90
+ try {
91
+ return await fn();
92
+ }
93
+ finally {
94
+ releaseWriteLane();
95
+ }
96
+ };
97
+ const rethrowFirst = (results) => {
98
+ for (const result of results) {
99
+ if (result.status === 'rejected')
100
+ throw result.reason;
101
+ }
102
+ };
103
+ // Fast path: accept only paths that cannot escape. Anything else
104
+ // falls through to relative()/resolve() so drive-relative and
105
+ // `./`-segment cases keep today's exact (platform/cwd-dependent)
106
+ // behavior.
107
+ const isClearlySafeRelPath = (sub) => {
108
+ const len = sub.length;
109
+ if (len === 0)
110
+ return true;
111
+ // leading /
112
+ if (sub.charCodeAt(0) === 47)
113
+ return false;
114
+ // <letter>: prefix (drive-relative)
115
+ if (len >= 2 && sub.charCodeAt(1) === 58) {
116
+ const c = sub.charCodeAt(0);
117
+ if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) {
118
+ return false;
119
+ }
120
+ }
121
+ let i = 0;
122
+ while (i < len) {
123
+ let j = i;
124
+ while (j < len && sub.charCodeAt(j) !== 47)
125
+ j++;
126
+ const slen = j - i;
127
+ if (slen === 1 && sub.charCodeAt(i) === 46)
128
+ return false;
129
+ if (slen === 2 &&
130
+ sub.charCodeAt(i) === 46 &&
131
+ sub.charCodeAt(i + 1) === 46) {
132
+ return false;
133
+ }
134
+ i = j + 1;
135
+ }
136
+ return true;
137
+ };
138
+ export const checkFs = (h, tarDir, target) => {
27
139
  if (!h.path)
28
140
  return false;
29
141
  if (!tarDir)
30
142
  return false;
31
- /* c8 ignore stop */
32
143
  h.path = h.path.replace(/[\\/]+/g, '/');
33
144
  // packages should always be in a 'package' tarDir in the archive
34
145
  if (!h.path.startsWith(tarDir))
35
146
  return false;
147
+ const sub = h.path.slice(tarDir.length);
148
+ if (isClearlySafeRelPath(sub))
149
+ return true;
36
150
  // entries must stay within the package root. separator-aware, so that
37
151
  // a sibling dir whose name extends the target's is not a prefix match.
38
- const rel = relative(target, resolve(target, h.path.slice(tarDir.length)));
152
+ const rel = relative(target, resolve(target, sub));
39
153
  if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
40
154
  return false;
41
155
  }
42
156
  return true;
43
157
  };
44
158
  const write = async (path, body, executable = false) => {
45
- await mkdirp(dirname(path));
46
159
  // if the mode is world-executable, then make it executable
47
160
  // this is needed for some packages that have a file that is
48
161
  // not a declared bin, but still used as a cli executable.
@@ -50,17 +163,6 @@ const write = async (path, body, executable = false) => {
50
163
  mode: executable ? 0o777 : 0o666,
51
164
  });
52
165
  };
53
- const made = new Set();
54
- const making = new Map();
55
- const mkdirp = async (d) => {
56
- if (!made.has(d)) {
57
- const m = making.get(d) ??
58
- mkdir(d, { recursive: true, mode: 0o777 }).then(() => making.delete(d));
59
- making.set(d, m);
60
- await m;
61
- made.add(d);
62
- }
63
- };
64
166
  export const unpack = async (tarData, target) => {
65
167
  const isGzip = tarData[0] === 0x1f && tarData[1] === 0x8b;
66
168
  await unpackUnzipped(isGzip ? await unzip(tarData) : tarData, target);
@@ -92,9 +194,9 @@ const unpackUnzipped = async (buffer, target) => {
92
194
  }
93
195
  const tmp = dirname(target) + sep + '.' + basename(target) + '.' + tmpSuffix();
94
196
  const og = tmp + '.ORIGINAL';
95
- await Promise.all([rimraf(tmp), rimraf(og)]);
96
197
  let succeeded = false;
97
198
  try {
199
+ const entries = new Map();
98
200
  let tarDir = undefined;
99
201
  let offset = 0;
100
202
  let h;
@@ -122,10 +224,23 @@ const unpackUnzipped = async (buffer, target) => {
122
224
  continue;
123
225
  if (!checkFs(h, tarDir, tmp))
124
226
  continue;
125
- await write(resolve(tmp, h.path.substring(tarDir.length)), body,
126
- // if it's world-executable, it's an executable
127
- // otherwise, make it read-only.
128
- 1 === ((h.mode ?? 0x666) & 1));
227
+ {
228
+ const dest = resolve(tmp, h.path.substring(tarDir.length));
229
+ const key = entryKey(dest);
230
+ // a repeated path is fine (last wins), but flipping between
231
+ // file and directory would silently discard data.
232
+ if (entries.get(key)?.dir === true) {
233
+ throw error('file/directory collision in tarball', {
234
+ path: dest,
235
+ });
236
+ }
237
+ entries.set(key, {
238
+ path: dest,
239
+ body,
240
+ executable: 1 === ((h.mode ?? 0x666) & 1),
241
+ dir: false,
242
+ });
243
+ }
129
244
  break;
130
245
  case 'Directory':
131
246
  /* c8 ignore next 2 */
@@ -135,7 +250,19 @@ const unpackUnzipped = async (buffer, target) => {
135
250
  continue;
136
251
  if (!checkFs(h, tarDir, tmp))
137
252
  continue;
138
- await mkdirp(resolve(tmp, h.path.substring(tarDir.length)));
253
+ {
254
+ const dest = resolve(tmp, h.path.substring(tarDir.length));
255
+ const key = entryKey(dest);
256
+ if (entries.get(key)?.dir === false) {
257
+ throw error('file/directory collision in tarball', {
258
+ path: dest,
259
+ });
260
+ }
261
+ entries.set(key, {
262
+ path: dest,
263
+ dir: true,
264
+ });
265
+ }
139
266
  break;
140
267
  case 'GlobalExtendedHeader':
141
268
  gex = Pax.parse(body.toString(), gex, true);
@@ -151,6 +278,21 @@ const unpackUnzipped = async (buffer, target) => {
151
278
  break;
152
279
  }
153
280
  }
281
+ // Per-unpack memo: paths are tmp-scoped and never reused across
282
+ // unpacks. The unique dir set is the memo; making/made globals
283
+ // previously leaked ~18k strings per install.
284
+ const dirs = new Set();
285
+ const files = [];
286
+ for (const e of entries.values()) {
287
+ if (e.dir)
288
+ dirs.add(e.path);
289
+ else {
290
+ dirs.add(dirname(e.path));
291
+ files.push(e);
292
+ }
293
+ }
294
+ rethrowFirst(await Promise.allSettled([...dirs].map(d => mkdir(d, { recursive: true, mode: 0o777 }))));
295
+ rethrowFirst(await Promise.allSettled(files.map(f => withWriteLane(() => write(f.path, f.body, f.executable)))));
154
296
  const targetExists = await exists(target);
155
297
  if (targetExists)
156
298
  await rename(target, og);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vltpkg/tar",
3
3
  "description": "An extremely limited and very fast tar extractor",
4
- "version": "1.0.2",
4
+ "version": "1.0.4",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,8 +13,8 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
16
- "@vltpkg/error-cause": "1.0.2",
17
- "@vltpkg/types": "1.0.2",
16
+ "@vltpkg/error-cause": "1.0.4",
17
+ "@vltpkg/types": "1.0.4",
18
18
  "rimraf": "^6.1.2",
19
19
  "tar": "^7.5.2"
20
20
  },