Skip to content

Commit d539172

Browse files
HichemTab-techCopilotzkochan
authored
fix(pack): compute packed summary before postpack cleanup (#12777)
--------- Co-authored-by: Copilot Autofix powered by AI <[email protected]> Co-authored-by: Zoltan Kochan <[email protected]>
1 parent dcabb78 commit d539172

6 files changed

Lines changed: 153 additions & 27 deletions

File tree

‎.changeset/forty-emus-run.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@pnpm/releasing.commands": patch
3+
"pnpm": patch
4+
---
5+
Fixed pnpm pack and pnpm publish failing when prepack generates files that are included in the package and postpack cleans them up.

‎.changeset/spicy-lions-guard.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@pnpm/releasing.commands": patch
3+
"pnpm": patch
4+
---
5+
6+
`pnpm pack` and `pnpm publish` no longer follow a symlinked workspace `LICENSE` file when injecting it into a package that has no license of its own. Following the symlink could pack bytes from outside the workspace into the published tarball.

‎pacquet/crates/pack/src/lib.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,14 @@ where
297297
path: dest_dir.display().to_string(),
298298
source,
299299
})?;
300+
}
301+
302+
// The size pass must run before `postpack`, which may delete
303+
// prepack-generated files that were packed. See pnpm/pnpm#12775.
304+
let unpacked_size = unpacked_size::<Sys>(&files_map, manifest_json.len() as u64)?;
305+
let contents = packed_contents(&files_map);
306+
307+
if !opts.dry_run {
300308
let bins = executable_sources(&publish_manifest, &manifest, &dir);
301309
let dest_file = dest_dir.join(&tarball_name);
302310
Sys::atomic_write(&dest_file, &mut |writer| {
@@ -318,8 +326,6 @@ where
318326
}
319327

320328
let tarball_path = packed_tarball_path(&opts.dir, &dir, &dest_dir, &tarball_name);
321-
let unpacked_size = unpacked_size::<Sys>(&files_map, manifest_json.len() as u64)?;
322-
let contents = packed_contents(&files_map);
323329

324330
Ok(PackResult { published_manifest: publish_manifest, contents, tarball_path, unpacked_size })
325331
}

‎pacquet/crates/pack/src/tests.rs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,36 @@ fn runs_prepack_prepare_and_postpack() {
478478
assert!(dir.path().join("postpack.ran").exists(), "postpack should have run");
479479
}
480480

481+
/// Regression test for <https://github.com/pnpm/pnpm/issues/12775>: the
482+
/// packed summary (`contents` / `unpacked_size`) is computed while
483+
/// prepack-generated files still exist on disk, so a `postpack` that
484+
/// cleans them up cannot fail the pack. Unix-gated like the other
485+
/// script-running tests, since it shells out through the platform shell.
486+
#[cfg(unix)]
487+
#[test]
488+
fn includes_prepack_generated_files_removed_by_postpack() {
489+
let (dir, mut opts) = fixture(&json!({
490+
"name": "foo",
491+
"version": "1.0.0",
492+
"files": ["generated.txt"],
493+
"scripts": {
494+
"prepack": "printf 'generated during prepack' > generated.txt",
495+
"postpack": "rm -f generated.txt",
496+
},
497+
}));
498+
opts.ignore_scripts = false;
499+
500+
let result = api::<SilentReporter, Host>(&opts).unwrap();
501+
502+
assert_eq!(result.contents, vec!["generated.txt".to_string(), "package.json".into()]);
503+
assert!(dir.path().join("foo-1.0.0.tgz").is_file());
504+
assert!(!dir.path().join("generated.txt").exists(), "postpack should clean the generated file");
505+
506+
let names = tarball_entry_names(&dir.path().join("foo-1.0.0.tgz"));
507+
dbg!(&names);
508+
assert!(names.contains(&"package/generated.txt".to_string()));
509+
}
510+
481511
/// With scripts enabled but the manifest declaring none of the
482512
/// requested lifecycle scripts (here an empty `prepack`), `script_body`
483513
/// yields `None` and `run_scripts_if_present` returns early, so packing

‎pnpm11/releasing/commands/src/publish/pack.ts‎

Lines changed: 44 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -275,16 +275,48 @@ export async function api (opts: PackOptions): Promise<PackResult> {
275275
const filesMap = Object.fromEntries(files.map((file) => [`package/${file}`, path.join(dir, file)]))
276276
// cspell:disable-next-line
277277
if (opts.workspaceDir != null && dir !== opts.workspaceDir && !files.some((file) => /LICEN[CS]E(?:\..+)?/i.test(file))) {
278-
const licenses = await glob([LICENSE_GLOB], { cwd: opts.workspaceDir, expandDirectories: false })
279-
for (const license of licenses) {
280-
filesMap[`package/${license}`] = path.join(opts.workspaceDir, license)
281-
}
278+
const { workspaceDir } = opts
279+
const licenses = await glob([LICENSE_GLOB], { cwd: workspaceDir, expandDirectories: false })
280+
await Promise.all(licenses.map(async (license) => {
281+
const licensePath = path.join(workspaceDir, license)
282+
// Only inject a regular file. A symlink could point outside the workspace and leak its
283+
// target's bytes into the published tarball, so `lstat()` (which does not follow symlinks)
284+
// rejects it — matching pacquet's inject_workspace_license.
285+
const stats = await fs.promises.lstat(licensePath)
286+
if (stats.isFile()) {
287+
filesMap[`package/${license}`] = licensePath
288+
}
289+
}))
282290
}
283291
const destDir = packDestination
284292
? (path.isAbsolute(packDestination) ? packDestination : path.join(dir, packDestination ?? '.'))
285293
: dir
286294
if (!opts.dryRun) {
287295
await fs.promises.mkdir(destDir, { recursive: true })
296+
}
297+
// Derive `contents` and `unpackedSize` from `filesMap` (the full set of tar entries) rather than
298+
// from `files` (the packlist subset) so that:
299+
// - workspace LICENSE files appended to `filesMap` after the packlist call are included; and
300+
// - `package.yaml` / `package.json5` entries are reported under the name they actually have in
301+
// the tar (`package.json`), since `packPkg()` rewrites them.
302+
// The `stat()` pass must run before `postpack`, which may delete prepack-generated files that
303+
// were packed. See https://github.com/pnpm/pnpm/issues/12775.
304+
const sizes = await Promise.all(Object.entries(filesMap).map(async ([name, source]) => {
305+
if (isManifestEntry(name)) {
306+
return Buffer.byteLength(JSON.stringify(publishManifest, null, 2))
307+
}
308+
const stat = await fs.promises.stat(source)
309+
return stat.size
310+
}))
311+
const unpackedSize = sizes.reduce((acc, size) => acc + size, 0)
312+
const packedContents = Array.from(new Set(
313+
Object.keys(filesMap).map((name) =>
314+
isManifestEntry(name)
315+
? 'package.json'
316+
: name.replace(/^package\//, '')
317+
)
318+
)).sort((a, b) => a.localeCompare(b, 'en'))
319+
if (!opts.dryRun) {
288320
await packPkg({
289321
destFile: path.join(destDir, tarballName),
290322
filesMap,
@@ -307,26 +339,6 @@ export async function api (opts: PackOptions): Promise<PackResult> {
307339
} else {
308340
packedTarballPath = path.relative(opts.dir, path.join(dir, tarballName))
309341
}
310-
// Derive `contents` and `unpackedSize` from `filesMap` (the full set of tar entries) rather than
311-
// from `files` (the packlist subset) so that:
312-
// - workspace LICENSE files appended to `filesMap` after the packlist call are included; and
313-
// - `package.yaml` / `package.json5` entries are reported under the name they actually have in
314-
// the tar (`package.json`), since `packPkg()` rewrites them.
315-
const sizes = await Promise.all(Object.entries(filesMap).map(async ([name, source]) => {
316-
if (/^package\/package\.(?:json|json5|yaml)$/.test(name)) {
317-
return Buffer.byteLength(JSON.stringify(publishManifest, null, 2))
318-
}
319-
const stat = await fs.promises.stat(source)
320-
return stat.size
321-
}))
322-
const unpackedSize = sizes.reduce((acc, size) => acc + size, 0)
323-
const packedContents = Array.from(new Set(
324-
Object.keys(filesMap).map((name) =>
325-
/^package\/package\.(?:json|json5|yaml)$/.test(name)
326-
? 'package.json'
327-
: name.replace(/^package\//, '')
328-
)
329-
)).sort((a, b) => a.localeCompare(b, 'en'))
330342
return {
331343
publishedManifest: publishManifest,
332344
contents: packedContents,
@@ -343,6 +355,13 @@ export interface PackResult {
343355
unpackedSize: number
344356
}
345357

358+
// True when a `package/<path>` tar key names the package manifest, which is
359+
// packed as a single serialized `package/package.json` entry and reported as
360+
// `package.json` in the contents listing regardless of the source file name.
361+
function isManifestEntry (name: string): boolean {
362+
return name === 'package/package.json' || name === 'package/package.json5' || name === 'package/package.yaml'
363+
}
364+
346365
function stripBuildMetadata (version: string): string {
347366
const plusIndex = version.indexOf('+')
348367
return plusIndex === -1 ? version : version.slice(0, plusIndex)
@@ -379,7 +398,7 @@ async function packPkg (opts: {
379398
await Promise.all(Object.entries(filesMap).map(async ([name, source]) => {
380399
const isExecutable = bins.some((bin) => path.relative(bin, source) === '')
381400
const mode = isExecutable ? 0o755 : 0o644
382-
if (/^package\/package\.(?:json|json5|yaml)$/.test(name)) {
401+
if (isManifestEntry(name)) {
383402
pack.entry({ mode, mtime, name: 'package/package.json' }, JSON.stringify(manifest, null, 2))
384403
return
385404
}

‎pnpm11/releasing/commands/test/publish/pack.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,66 @@ test('pack: runs prepack, prepare, and postpack', async () => {
367367
expect(fs.existsSync('postpack')).toBeTruthy()
368368
})
369369

370+
test('pack: includes prepack-generated files removed by postpack', async () => {
371+
prepare({
372+
name: 'prepack-generated-postpack-cleaned',
373+
version: '0.0.0',
374+
files: ['generated.txt'],
375+
scripts: {
376+
prepack: 'node -e "require(\'fs\').writeFileSync(\'generated.txt\', \'generated during prepack\')"',
377+
postpack: 'node -e "require(\'fs\').rmSync(\'generated.txt\', { force: true })"',
378+
},
379+
})
380+
381+
const output = await pack.handler({
382+
...DEFAULT_OPTS,
383+
argv: { original: [] },
384+
dir: process.cwd(),
385+
extraBinPaths: [],
386+
packDestination: process.cwd(),
387+
})
388+
389+
expect(output).toContain('generated.txt')
390+
expect(fs.existsSync('prepack-generated-postpack-cleaned-0.0.0.tgz')).toBeTruthy()
391+
expect(fs.existsSync('generated.txt')).toBeFalsy()
392+
393+
await tar.x({ file: 'prepack-generated-postpack-cleaned-0.0.0.tgz' })
394+
395+
expect(fs.existsSync('package/generated.txt')).toBeTruthy()
396+
})
397+
398+
// A symlinked workspace-root LICENSE must not be injected: following it would
399+
// leak the target's bytes — potentially a file outside the workspace — into
400+
// the published tarball.
401+
;(process.platform === 'win32' ? test.skip : test)('pack: does not inject a symlinked workspace LICENSE', async () => {
402+
preparePackages([
403+
{
404+
name: 'project',
405+
version: '1.0.0',
406+
},
407+
])
408+
409+
const workspaceDir = process.cwd()
410+
writeYamlFileSync('pnpm-workspace.yaml', { packages: ['**', '!store/**'] })
411+
fs.writeFileSync('secret.txt', 'host secret', 'utf8')
412+
fs.symlinkSync(path.join(workspaceDir, 'secret.txt'), path.join(workspaceDir, 'LICENSE'))
413+
414+
process.chdir('project')
415+
const output = await pack.handler({
416+
...DEFAULT_OPTS,
417+
argv: { original: [] },
418+
dir: process.cwd(),
419+
extraBinPaths: [],
420+
workspaceDir,
421+
})
422+
423+
expect(output).not.toContain('LICENSE')
424+
425+
await tar.x({ file: 'project-1.0.0.tgz' })
426+
427+
expect(fs.existsSync('package/LICENSE')).toBeFalsy()
428+
})
429+
370430
const modeIsExecutable = (mode: number) => (mode & 0o111) === 0o111
371431

372432
;(process.platform === 'win32' ? test.skip : test)('the mode of executable is changed', async () => {

0 commit comments

Comments
 (0)