From b7f6e5f0285515087b4614d81db17206524c0fdb Mon Sep 17 00:00:00 2001 From: isaacs Date: Thu, 15 Aug 2019 11:14:11 -0700 Subject: [PATCH] Infer ownership of shrinkwrap files Do not leave a root-owned package-lock or npm-shrinkwrap file in the project root, where it will create problems when the user tries to update it later. --- lib/shrinkwrap.js | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/lib/shrinkwrap.js b/lib/shrinkwrap.js index 35e063d447956..0a3f53546ca87 100644 --- a/lib/shrinkwrap.js +++ b/lib/shrinkwrap.js @@ -25,6 +25,13 @@ const writeFileAtomic = require('write-file-atomic') const unixFormatPath = require('./utils/unix-format-path.js') const isRegistry = require('./utils/is-registry.js') +const { chown } = require('fs') +const inferOwner = require('infer-owner') +const selfOwner = { + uid: process.getuid && process.getuid(), + gid: process.getgid && process.getgid() +} + const PKGLOCK = 'package-lock.json' const SHRINKWRAP = 'npm-shrinkwrap.json' const PKGLOCK_VERSION = npm.lockfileVersion @@ -217,13 +224,19 @@ function save (dir, pkginfo, opts, cb) { log.verbose('shrinkwrap', `skipping write for ${path.basename(info.path)} because there were no changes.`) cb(null, pkginfo) } else { - writeFileAtomic(info.path, swdata, (err) => { - if (err) return cb(err) - if (opts.silent) return cb(null, pkginfo) - if (!shrinkwrap && !lockfile) { - log.notice('', `created a lockfile as ${path.basename(info.path)}. You should commit this file.`) - } - cb(null, pkginfo) + inferOwner(info.path).then(owner => { + writeFileAtomic(info.path, swdata, (err) => { + if (err) return cb(err) + if (opts.silent) return cb(null, pkginfo) + if (!shrinkwrap && !lockfile) { + log.notice('', `created a lockfile as ${path.basename(info.path)}. You should commit this file.`) + } + if (selfOwner.uid === 0 && (selfOwner.uid !== owner.uid || selfOwner.gid !== owner.gid)) { + chown(info.path, owner.uid, owner.gid, er => cb(er, pkginfo)) + } else { + cb(null, pkginfo) + } + }) }) } }