@pnpm/fs.packlist 1100.0.6 → 1100.0.8

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.
Files changed (3) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/lib/index.js +126 -103
  3. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @pnpm/fs.packlist
2
2
 
3
+ ## 1100.0.8
4
+
5
+ ### Patch Changes
6
+
7
+ - Prevent bundled dependencies from traversing escaping directory symlinks or packaging files outside the package root [pnpm/tasks#83](https://github.com/pnpm/tasks/issues/83) [pnpm/tasks#93](https://github.com/pnpm/tasks/issues/93).
8
+
9
+ - Updated dependencies:
10
+ - @pnpm/error@1100.2.2
11
+ - @pnpm/workspace.project-manifest-reader@1100.1.3
12
+
13
+ ## 1100.0.7
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies:
18
+ - @pnpm/workspace.project-manifest-reader@1100.1.2
19
+
3
20
  ## 1100.0.6
4
21
 
5
22
  ### Patch Changes
package/lib/index.js CHANGED
@@ -52,24 +52,15 @@ class PackWalker extends npmPacklist.Walker {
52
52
  if (!Array.isArray(files))
53
53
  return [];
54
54
  const rules = [];
55
- for (let file of files) {
56
- if (file.startsWith('!'))
55
+ for (const entry of files) {
56
+ if (entry.startsWith('!'))
57
57
  continue;
58
- if (file.startsWith('./'))
59
- file = file.slice(1);
60
- let stat;
61
- try {
62
- stat = fs.lstatSync(path.join(this.path, file));
63
- }
64
- catch (err) {
65
- if (isError(err) && 'code' in err && (err.code === 'ENOENT' || err.code === 'ENOTDIR'))
66
- continue;
67
- throw err;
68
- }
69
- if (stat.isSymbolicLink()) {
70
- rules.push(`!${file}`);
71
- this.requiredFiles.push(file.startsWith('/') ? file.slice(1) : file);
72
- }
58
+ const file = entry.startsWith('./') ? entry.slice(1) : entry;
59
+ const stat = lstatIfExists(path.join(this.path, file), ['ENOENT', 'ENOTDIR']);
60
+ if (!stat?.isSymbolicLink())
61
+ continue;
62
+ rules.push(`!${file}`);
63
+ this.requiredFiles.push(file.startsWith('/') ? file.slice(1) : file);
73
64
  }
74
65
  return rules;
75
66
  }
@@ -102,58 +93,62 @@ export async function packlistWithSources(pkgDir, opts) {
102
93
  const hasWorkspaceContext = workspaceDir != null && workspaceDir !== resolvedPkgDir && isSubdir(workspaceDir, resolvedPkgDir);
103
94
  const boundary = hasWorkspaceContext ? workspaceDir : path.resolve(opts?.bundledDependenciesDir ?? resolvedPkgDir);
104
95
  const { tree, packedDirs } = buildRootTree(resolvedPkgDir, pkg, boundary);
105
- let hasNpmIgnore = false;
106
- if (hasWorkspaceContext) {
107
- try {
108
- hasNpmIgnore = (await fs.promises.stat(path.join(resolvedPkgDir, '.npmignore'))).isFile();
109
- }
110
- catch (err) {
111
- if (!isError(err) || !('code' in err) || err.code !== 'ENOENT')
112
- throw err;
113
- }
114
- }
115
- const packlistOpts = hasWorkspaceContext && !hasNpmIgnore
96
+ const packlistOpts = hasWorkspaceContext && !await hasNpmIgnoreFile(resolvedPkgDir)
116
97
  ? { prefix: workspaceDir, workspaces: [resolvedPkgDir] }
117
98
  : undefined;
118
- const walkedFiles = await new Promise((resolve, reject) => {
99
+ const files = (await walkPackage(tree, packlistOpts))
100
+ .map((file) => file.replace(/^\.[/\\]/, ''))
101
+ .filter((file) => isInternalFileOrSymlink(resolvedPkgDir, file, boundary));
102
+ return mapToPackedPaths(resolvedPkgDir, files, packedDirs);
103
+ }
104
+ async function hasNpmIgnoreFile(pkgDir) {
105
+ try {
106
+ return (await fs.promises.stat(path.join(pkgDir, '.npmignore'))).isFile();
107
+ }
108
+ catch (err) {
109
+ if (!isError(err) || !('code' in err) || err.code !== 'ENOENT')
110
+ throw err;
111
+ return false;
112
+ }
113
+ }
114
+ async function walkPackage(tree, packlistOpts) {
115
+ return new Promise((resolve, reject) => {
119
116
  new PackWalker(tree, { ...packlistOpts, isPackage: true })
120
117
  .on('done', resolve)
121
118
  .on('error', reject)
122
119
  .start();
123
120
  });
124
- const files = walkedFiles
125
- .map((file) => file.replace(/^\.[/\\]/, ''))
126
- .filter((file) => isInternalFileOrSymlink(resolvedPkgDir, file));
127
- return mapToPackedPaths(resolvedPkgDir, files, packedDirs);
128
121
  }
129
122
  function isEscapingRelativePath(rel) {
130
123
  return rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel);
131
124
  }
132
- function isInternalFileOrSymlink(pkgDir, relFile) {
125
+ function isInternalFileOrSymlink(pkgDir, relFile, boundary = pkgDir) {
133
126
  const absPath = path.join(pkgDir, relFile);
134
- let lstat;
127
+ const lstat = lstatIfExists(absPath, ['ENOENT']);
128
+ if (lstat == null) {
129
+ return false;
130
+ }
131
+ if (!lstat.isSymbolicLink()) {
132
+ return !realTargetEscapes(boundary, absPath, false);
133
+ }
134
+ return isInternalSymlink(pkgDir, relFile, absPath, boundary);
135
+ }
136
+ function lstatIfExists(filePath, missingCodes) {
135
137
  try {
136
- lstat = fs.lstatSync(absPath);
138
+ return fs.lstatSync(filePath);
137
139
  }
138
140
  catch (err) {
139
- if (isError(err) && 'code' in err && err.code === 'ENOENT')
140
- return false;
141
+ if (isError(err) && 'code' in err && missingCodes.includes(err.code))
142
+ return undefined;
141
143
  throw err;
142
144
  }
143
- if (!lstat.isSymbolicLink()) {
144
- return true;
145
- }
145
+ }
146
+ function isInternalSymlink(pkgDir, relFile, absPath, boundary = pkgDir) {
146
147
  let linkTarget = fs.readlinkSync(absPath);
147
148
  if (path.isAbsolute(linkTarget)) {
148
149
  linkTarget = path.relative(path.dirname(absPath), linkTarget);
149
150
  }
150
- const relPosix = process.platform === 'win32' ? relFile.replace(/\\/g, '/') : relFile;
151
- const posixTarget = linkTarget.replace(/\\/g, '/');
152
- if (path.posix.isAbsolute(posixTarget)) {
153
- return false;
154
- }
155
- const normalizedArchive = path.posix.normalize(path.posix.join(path.posix.dirname(relPosix), posixTarget));
156
- if (normalizedArchive === '..' || normalizedArchive.startsWith('../')) {
151
+ if (archivedLinkEscapes(relFile, linkTarget)) {
157
152
  return false;
158
153
  }
159
154
  const resolvedTarget = path.resolve(path.dirname(absPath), linkTarget);
@@ -161,20 +156,29 @@ function isInternalFileOrSymlink(pkgDir, relFile) {
161
156
  if (isEscapingRelativePath(relToPkg)) {
162
157
  return false;
163
158
  }
159
+ return !realTargetEscapes(boundary, absPath, true);
160
+ }
161
+ function archivedLinkEscapes(relFile, linkTarget) {
162
+ const relPosix = process.platform === 'win32' ? relFile.replace(/\\/g, '/') : relFile;
163
+ const posixTarget = linkTarget.replace(/\\/g, '/');
164
+ if (path.posix.isAbsolute(posixTarget)) {
165
+ return true;
166
+ }
167
+ const normalizedArchive = path.posix.normalize(path.posix.join(path.posix.dirname(relPosix), posixTarget));
168
+ return normalizedArchive === '..' || normalizedArchive.startsWith('../');
169
+ }
170
+ function realTargetEscapes(boundary, absPath, isSymlink = true) {
171
+ const realBoundary = realpathOrUndefined(boundary) ?? boundary;
164
172
  try {
165
173
  const realTarget = fs.realpathSync(absPath);
166
- const realPkgDir = fs.realpathSync(pkgDir);
167
- const relReal = path.relative(realPkgDir, realTarget);
168
- if (isEscapingRelativePath(relReal)) {
169
- return false;
170
- }
174
+ return isEscapingRelativePath(path.relative(realBoundary, realTarget));
171
175
  }
172
176
  catch (err) {
173
177
  if (!isError(err) || !('code' in err) || err.code !== 'ENOENT') {
174
178
  throw err;
175
179
  }
180
+ return !isSymlink;
176
181
  }
177
- return true;
178
182
  }
179
183
  function mapToPackedPaths(pkgDir, files, packedDirs) {
180
184
  const bundleDirs = Array.from(packedDirs, ([node, packed]) => ({
@@ -204,7 +208,7 @@ function mapToPackedPaths(pkgDir, files, packedDirs) {
204
208
  * separately by packedLocation().
205
209
  */
206
210
  function buildRootTree(pkgDir, pkg, boundary) {
207
- const bundledDeps = getRootBundledDeps(pkg);
211
+ const bundledDeps = getRootBundledDeps(pkg).filter(isSafeBundleName);
208
212
  // npm-packlist's gatherBundles() iterates package.bundleDependencies directly,
209
213
  // so the field must be an array. Normalize true/undefined to an explicit list.
210
214
  const normalizedPkg = normalizePackage(pkg);
@@ -225,29 +229,38 @@ function buildRootTree(pkgDir, pkg, boundary) {
225
229
  const task = queue.shift();
226
230
  if (task.depth > MAX_BUNDLE_DEPTH)
227
231
  continue;
228
- const resolved = resolveDependency(task.name, task.parent.realDir, walk.boundary);
229
- if (resolved == null)
230
- continue;
231
- const packed = packedLocation(walk, task.name, task.parent.packed, resolved.realDir);
232
- if (packed == null)
232
+ const placed = placeBundledDependency(walk, task);
233
+ if (placed == null)
233
234
  continue;
234
- let node = walk.nodes.get(resolved.realDir);
235
- if (node == null) {
236
- const dir = isSubdir(walk.realPkgDir, resolved.dir) ? path.join(pkgDir, path.relative(walk.realPkgDir, resolved.dir)) : resolved.dir;
237
- node = makeNode(dir, normalizePackage(readPackageJson(dir)), false);
238
- walk.nodes.set(resolved.realDir, node);
239
- walk.packedDirs.set(node, []);
240
- }
241
- task.parent.node.edgesOut.set(task.name, { to: node, peer: false, dev: false });
242
- walk.packedDirs.get(node).push(packedDir(packed));
243
- walk.slots.set(packed.join('\0'), resolved.realDir);
244
- const placed = { packed, realDir: resolved.realDir, node };
245
- for (const name of getNestedBundledDeps(node.package)) {
235
+ for (const name of getNestedBundledDeps(placed.node.package)) {
246
236
  queue.push({ name, parent: placed, depth: task.depth + 1 });
247
237
  }
248
238
  }
249
239
  return { tree: root, packedDirs: walk.packedDirs };
250
240
  }
241
+ function placeBundledDependency(walk, task) {
242
+ const resolved = resolveDependency(task.name, task.parent.realDir, walk.boundary);
243
+ if (resolved == null)
244
+ return undefined;
245
+ const packed = packedLocation(walk, task.name, task.parent.packed, resolved.realDir);
246
+ if (packed == null)
247
+ return undefined;
248
+ const node = getOrCreateBundleNode(walk, resolved);
249
+ task.parent.node.edgesOut.set(task.name, { to: node, peer: false, dev: false });
250
+ walk.packedDirs.get(node).push(packedDir(packed));
251
+ walk.slots.set(packed.join('\0'), resolved.realDir);
252
+ return { packed, realDir: resolved.realDir, node };
253
+ }
254
+ function getOrCreateBundleNode(walk, resolved) {
255
+ const existing = walk.nodes.get(resolved.realDir);
256
+ if (existing != null)
257
+ return existing;
258
+ const dir = isSubdir(walk.realPkgDir, resolved.dir) ? path.join(walk.pkgDir, path.relative(walk.realPkgDir, resolved.dir)) : resolved.dir;
259
+ const node = makeNode(dir, normalizePackage(readPackageJson(dir)), false);
260
+ walk.nodes.set(resolved.realDir, node);
261
+ walk.packedDirs.set(node, []);
262
+ return node;
263
+ }
251
264
  const MAX_BUNDLE_DEPTH = 32;
252
265
  /**
253
266
  * The packed location for a dependency required from the package packed at
@@ -288,21 +301,22 @@ function packedNames(pkgDir, dir) {
288
301
  while (segments.length > 0) {
289
302
  if (segments.shift() !== 'node_modules')
290
303
  return undefined;
291
- const name = segments.shift();
292
- if (name == null || name.startsWith('.'))
304
+ const name = shiftPackageName(segments);
305
+ if (name == null)
293
306
  return undefined;
294
- if (name.startsWith('@')) {
295
- const scopedName = segments.shift();
296
- if (scopedName == null)
297
- return undefined;
298
- names.push(`${name}/${scopedName}`);
299
- }
300
- else {
301
- names.push(name);
302
- }
307
+ names.push(name);
303
308
  }
304
309
  return names;
305
310
  }
311
+ function shiftPackageName(segments) {
312
+ const name = segments.shift();
313
+ if (name == null || name.startsWith('.'))
314
+ return undefined;
315
+ if (!name.startsWith('@'))
316
+ return name;
317
+ const scopedName = segments.shift();
318
+ return scopedName == null ? undefined : `${name}/${scopedName}`;
319
+ }
306
320
  function makeNode(pkgDir, pkg, isProjectRoot) {
307
321
  const node = {
308
322
  path: pkgDir,
@@ -326,30 +340,16 @@ function getRootBundledDeps(pkg) {
326
340
  function getNestedBundledDeps(pkg) {
327
341
  const dependencies = (pkg.dependencies ?? {});
328
342
  const optionalDependencies = (pkg.optionalDependencies ?? {});
329
- return [...Object.keys(dependencies), ...Object.keys(optionalDependencies)];
343
+ return [...Object.keys(dependencies), ...Object.keys(optionalDependencies)].filter(isSafeBundleName);
330
344
  }
331
345
  function resolveDependency(depName, fromDir, boundary) {
332
346
  if (!isSafeBundleName(depName))
333
347
  return undefined;
334
348
  let currentDir = fromDir;
335
349
  while (true) {
336
- if (path.basename(currentDir) !== 'node_modules') {
337
- const candidate = path.join(currentDir, 'node_modules', depName);
338
- try {
339
- const stat = fs.statSync(path.join(candidate, 'package.json'));
340
- if (stat.isFile()) {
341
- const realDir = fs.realpathSync(candidate);
342
- if (realDir !== boundary && !isSubdir(boundary, realDir))
343
- return undefined;
344
- return { dir: candidate, realDir };
345
- }
346
- }
347
- catch (err) {
348
- if (!isError(err) || !('code' in err) || err.code !== 'ENOENT') {
349
- throw err;
350
- }
351
- }
352
- }
350
+ const found = findInNodeModulesOf(currentDir, depName);
351
+ if (found != null)
352
+ return keepWithinBoundary(found, boundary);
353
353
  if (currentDir === boundary)
354
354
  return undefined;
355
355
  const parent = path.dirname(currentDir);
@@ -358,6 +358,29 @@ function resolveDependency(depName, fromDir, boundary) {
358
358
  currentDir = parent;
359
359
  }
360
360
  }
361
+ function keepWithinBoundary(resolved, boundary) {
362
+ return resolved.realDir === boundary || isSubdir(boundary, resolved.realDir) ? resolved : undefined;
363
+ }
364
+ function findInNodeModulesOf(dir, depName) {
365
+ if (path.basename(dir) === 'node_modules')
366
+ return undefined;
367
+ const candidate = path.join(dir, 'node_modules', depName);
368
+ const realDir = realpathOfPackageDir(candidate);
369
+ return realDir == null ? undefined : { dir: candidate, realDir };
370
+ }
371
+ function realpathOfPackageDir(dir) {
372
+ try {
373
+ if (!fs.statSync(path.join(dir, 'package.json')).isFile())
374
+ return undefined;
375
+ return fs.realpathSync(dir);
376
+ }
377
+ catch (err) {
378
+ if (!isError(err) || !('code' in err) || err.code !== 'ENOENT') {
379
+ throw err;
380
+ }
381
+ return undefined;
382
+ }
383
+ }
361
384
  // Bundle names come from package.json, so reject paths before joining them under node_modules.
362
385
  function isSafeBundleName(name) {
363
386
  if (typeof name !== 'string' || name.includes('\\'))
@@ -388,8 +411,8 @@ function readPackageJson(dir) {
388
411
  throw err;
389
412
  }
390
413
  }
391
- function stripDotSlash(p) {
392
- return p.replace(/^\.[/\\]/, '');
414
+ function stripDotSlash(filePath) {
415
+ return filePath.replace(/^\.[/\\]/, '');
393
416
  }
394
417
  function normalizePackage(pkg) {
395
418
  const normalized = { ...pkg };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pnpm/fs.packlist",
3
- "version": "1100.0.6",
3
+ "version": "1100.0.8",
4
4
  "description": "Get a list of the files to add from a directory into an npm package",
5
5
  "keywords": [
6
6
  "pnpm",
@@ -27,13 +27,13 @@
27
27
  "!*.map"
28
28
  ],
29
29
  "dependencies": {
30
- "@pnpm/error": "1100.2.1",
31
- "@pnpm/workspace.project-manifest-reader": "1100.1.1",
32
- "is-subdir": "^2.0.0",
30
+ "@pnpm/error": "1100.2.2",
31
+ "@pnpm/workspace.project-manifest-reader": "1100.1.3",
32
+ "is-subdir": "^2.0.1",
33
33
  "npm-packlist": "10.0.4"
34
34
  },
35
35
  "devDependencies": {
36
- "@pnpm/fs.packlist": "1100.0.6"
36
+ "@pnpm/fs.packlist": "1100.0.8"
37
37
  },
38
38
  "engines": {
39
39
  "node": ">=22.13"