Skip to content

Commit 9420673

Browse files
feat(install-scripts): prune unused allowScripts entries (#9662)
Backport of #9651 to `release/v11`. Co-authored-by: Jamie Magee <[email protected]>
1 parent 4c9eacb commit 9420673

8 files changed

Lines changed: 398 additions & 11 deletions

File tree

‎docs/lib/content/commands/npm-install-scripts.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,15 @@ contexts, use the `--allow-scripts` flag at install time (for example
2828
`npm install -g --allow-scripts=canvas,sharp`) or persist the setting with
2929
`npm config set allow-scripts=canvas,sharp --location=user`.
3030

31-
There are three subcommands:
31+
There are four subcommands:
3232

3333
```bash
3434
npm install-scripts approve <pkg> [<pkg> ...]
3535
npm install-scripts approve --all
3636
npm install-scripts deny <pkg> [<pkg> ...]
3737
npm install-scripts deny --all
3838
npm install-scripts ls
39+
npm install-scripts prune
3940
```
4041

4142
`approve` allows install scripts for the named packages. `<pkg>` matches
@@ -53,6 +54,14 @@ unreviewed install scripts.
5354
`ls` is read-only: it lists every package whose install scripts are not yet
5455
covered by `allowScripts`, without modifying `package.json`.
5556

57+
`prune` removes `allowScripts` entries that no longer match an installed
58+
package with an install script, either because the package is no longer
59+
installed (a transitive dependency changed, or a pinned `[email protected]` was
60+
upgraded) or because it no longer has an install script. Both approvals
61+
(`true`) and denials (`false`) are removed. It edits only the `allowScripts`
62+
field in `package.json`, never `.npmrc` or `--allow-scripts`. Pass `--dry-run`
63+
to preview without writing. Unparseable keys are left alone.
64+
5665
`approve` honours the asymmetric pin rule: if you re-approve a package whose
5766
installed version has changed, the existing pin is rewritten to track the new
5867
installed version. Multi-version statements (`pkg@1 || 2`) are left alone,
@@ -78,6 +87,10 @@ npm install-scripts deny telemetry-pkg
7887

7988
# Preview which packages still need review
8089
npm install-scripts ls
90+
91+
# Preview stale allowScripts entries, then remove them
92+
npm install-scripts prune --dry-run
93+
npm install-scripts prune
8194
```
8295

8396
### Configuration

‎lib/commands/install-scripts.js‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
const AllowScriptsCmd = require('../utils/allow-scripts-cmd.js')
22

3-
// Namespaced front-end for managing install-script approvals.
4-
// `approve` and `deny` write the `allowScripts` policy; `ls` lists packages with unreviewed install scripts.
5-
// The standalone `npm approve-scripts` and `npm deny-scripts` commands remain as aliases for `approve` and `deny`.
3+
// Namespaced front-end for install-script approvals.
4+
// `approve`/`deny` write the `allowScripts` policy, `ls` lists unreviewed packages,
5+
// `prune` drops entries that no longer match an installed package with an install script.
6+
// `npm approve-scripts` / `npm deny-scripts` are aliases for `approve` / `deny`.
67
class InstallScripts extends AllowScriptsCmd {
78
static description = 'Manage install-script approvals for dependencies'
89
static name = 'install-scripts'
@@ -12,13 +13,14 @@ class InstallScripts extends AllowScriptsCmd {
1213
'deny <pkg> [<pkg> ...]',
1314
'deny --all',
1415
'ls',
16+
'prune',
1517
]
1618

17-
static params = ['all', 'allow-scripts-pin', 'json']
19+
static params = ['all', 'allow-scripts-pin', 'dry-run', 'json']
1820

1921
static async completion (opts) {
2022
const argv = opts.conf.argv.remain
21-
const subcommands = ['approve', 'deny', 'ls']
23+
const subcommands = ['approve', 'deny', 'ls', 'prune']
2224
if (argv.length === 2) {
2325
return subcommands
2426
}
@@ -38,6 +40,8 @@ class InstallScripts extends AllowScriptsCmd {
3840
case 'ls':
3941
case 'list':
4042
return this.runMode('list', rest)
43+
case 'prune':
44+
return this.runMode('prune', rest)
4145
default:
4246
throw this.usageError(
4347
sub ? `\`${sub}\` is not a recognized subcommand.` : undefined

‎lib/utils/allow-scripts-cmd.js‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@ const npa = require('npm-package-arg')
33
const semver = require('semver')
44
const pkgJson = require('@npmcli/package-json')
55
const { trustedDisplay } = require('@npmcli/arborist/lib/script-allowed.js')
6+
const getInstallScripts = require('@npmcli/arborist/lib/install-scripts.js')
67
const checkAllowScripts = require('./check-allow-scripts.js')
78
const resolveAllowScripts = require('./resolve-allow-scripts.js')
89
const {
910
applyApprovalForPackage,
1011
applyDenyForPackage,
1112
nameKeyFor,
1213
} = require('./allow-scripts-writer.js')
14+
const { classifyUnusedEntries } = require('./allow-scripts-prune.js')
1315
const BaseCommand = require('../base-cmd.js')
1416

1517
// Parse a positional arg into a name and an optional version range. A bare
@@ -50,7 +52,7 @@ class AllowScriptsCmd extends BaseCommand {
5052
static ignoreImplicitWorkspace = false
5153

5254
// Mode of the current run, set by runMode.
53-
// One of 'approve', 'deny', or 'list'.
55+
// One of 'approve', 'deny', 'list', or 'prune'.
5456
#mode = null
5557

5658
// verb drives the writers and summaries, which only run in the two write modes, so it is never read while listing.
@@ -73,6 +75,12 @@ class AllowScriptsCmd extends BaseCommand {
7375
)
7476
}
7577

78+
// `prune` has its own flow: it reads the literal package.json#allowScripts
79+
// map, not the resolved policy.
80+
if (mode === 'prune') {
81+
return this.runPrune(args)
82+
}
83+
7684
// `--allow-scripts-pending` is only honored by commands that declare it; the namespace lists via `ls` instead.
7785
const pending = this.constructor.params.includes('allow-scripts-pending') &&
7886
!!this.npm.config.get('allow-scripts-pending')
@@ -318,6 +326,78 @@ class AllowScriptsCmd extends BaseCommand {
318326
output.standard(`Nothing to ${this.verb}; allowScripts unchanged.`)
319327
}
320328
}
329+
330+
// `npm install-scripts prune`: drop package.json#allowScripts entries that no
331+
// longer match an installed package with an install script. Edits only
332+
// package.json (never `.npmrc`/CLI policy); `--dry-run` reports without writing.
333+
async runPrune (args) {
334+
const all = !!this.npm.config.get('all')
335+
if (args.length > 0 || all) {
336+
throw this.usageError(
337+
'`npm install-scripts prune` cannot be combined with positional arguments or `--all`.'
338+
)
339+
}
340+
341+
const dryRun = !!this.npm.config.get('dry-run')
342+
const pkg = await pkgJson.load(this.npm.prefix)
343+
const existing = pkg.content.allowScripts && typeof pkg.content.allowScripts === 'object'
344+
? pkg.content.allowScripts
345+
: {}
346+
347+
let removed = []
348+
if (Object.keys(existing).length > 0) {
349+
const Arborist = require('@npmcli/arborist')
350+
const arb = new Arborist({
351+
...this.npm.flatOptions,
352+
path: this.npm.prefix,
353+
})
354+
await arb.loadActual()
355+
356+
// Candidate install nodes (mirrors collectUnreviewedScripts), tagged with
357+
// whether each has install scripts so the classifier can tell "gone" from
358+
// "no longer has scripts".
359+
const nodes = []
360+
for (const node of arb.actualTree.inventory.values()) {
361+
if (node.isProjectRoot || node.isWorkspace || node.isLink || node.inBundle || node.inert) {
362+
continue
363+
}
364+
const scripts = await getInstallScripts(node)
365+
nodes.push({ node, hasScripts: Object.keys(scripts).length > 0 })
366+
}
367+
368+
const { remaining, removed: unused } = classifyUnusedEntries(existing, nodes)
369+
removed = unused
370+
371+
if (removed.length > 0 && !dryRun) {
372+
// Drop the field entirely when nothing is left rather than leaving `{}`.
373+
pkg.update({
374+
allowScripts: Object.keys(remaining).length > 0 ? remaining : undefined,
375+
})
376+
await pkg.save()
377+
}
378+
}
379+
380+
this.printPruneSummary({ removed, dryRun })
381+
}
382+
383+
printPruneSummary ({ removed, dryRun }) {
384+
if (this.npm.flatOptions.json) {
385+
output.buffer({ allowScripts: { removed, dryRun } })
386+
return
387+
}
388+
if (removed.length === 0) {
389+
output.standard('No unused allowScripts entries.')
390+
return
391+
}
392+
const entry = removed.length === 1 ? 'entry' : 'entries'
393+
output.standard(
394+
`${dryRun ? 'Would remove' : 'Removed'} ${removed.length} unused allowScripts ${entry}:`
395+
)
396+
for (const { key, reason } of removed) {
397+
const text = reason === 'not-installed' ? 'package not installed' : 'no install scripts'
398+
output.standard(` ${key} (${text})`)
399+
}
400+
}
321401
}
322402

323403
module.exports = AllowScriptsCmd

‎lib/utils/allow-scripts-prune.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const npa = require('npm-package-arg')
2+
const { matches } = require('@npmcli/arborist/lib/script-allowed.js')
3+
4+
// Pure classifier behind `npm install-scripts prune`.
5+
//
6+
// Splits the `package.json#allowScripts` map into entries to keep (`remaining`)
7+
// and unused ones to drop (`removed`). `nodes` is the install candidates as
8+
// `{ node, hasScripts }`; the caller gathers them so this stays sync.
9+
//
10+
// An entry is unused (version-aware, by trusted identity) when:
11+
// - no installed node matches the key -> reason 'not-installed'
12+
// - it matches but none have scripts -> reason 'no-scripts'
13+
//
14+
// Unparseable keys are kept (prune never drops what it can't parse). Both
15+
// `true` (approve) and `false` (deny) entries are pruned.
16+
const classifyUnusedEntries = (allowScripts, nodes) => {
17+
const remaining = {}
18+
const removed = []
19+
20+
for (const [key, value] of Object.entries(allowScripts || {})) {
21+
let parseable = true
22+
try {
23+
npa(key)
24+
} catch {
25+
parseable = false
26+
}
27+
if (!parseable) {
28+
remaining[key] = value
29+
continue
30+
}
31+
32+
const matching = nodes.filter(({ node }) => matches(node, key))
33+
if (matching.length === 0) {
34+
removed.push({ key, value, reason: 'not-installed' })
35+
continue
36+
}
37+
if (!matching.some(({ hasScripts }) => hasScripts)) {
38+
removed.push({ key, value, reason: 'no-scripts' })
39+
continue
40+
}
41+
remaining[key] = value
42+
}
43+
44+
return { remaining, removed }
45+
}
46+
47+
module.exports = { classifyUnusedEntries }

‎tap-snapshots/test/lib/docs.js.test.cjs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4597,16 +4597,20 @@ npm install-scripts approve --all
45974597
npm install-scripts deny <pkg> [<pkg> ...]
45984598
npm install-scripts deny --all
45994599
npm install-scripts ls
4600+
npm install-scripts prune
46004601
46014602
Options:
4602-
[-a|--all] [--no-allow-scripts-pin] [--json]
4603+
[-a|--all] [--no-allow-scripts-pin] [--dry-run] [--json]
46034604
46044605
-a|--all
46054606
Show or act on all packages, not just the ones your project directly
46064607
46074608
--allow-scripts-pin
46084609
Write pinned (\`pkg@version\`) entries when approving install scripts.
46094610
4611+
--dry-run
4612+
Indicates that you don't want npm to make any changes and that it should
4613+
46104614
--json
46114615
Whether or not to output JSON data, rather than the normal output.
46124616
@@ -4619,12 +4623,14 @@ npm install-scripts approve --all
46194623
npm install-scripts deny <pkg> [<pkg> ...]
46204624
npm install-scripts deny --all
46214625
npm install-scripts ls
4626+
npm install-scripts prune
46224627
\`\`\`
46234628
46244629
Note: This command is unaware of workspaces.
46254630
46264631
#### \`all\`
46274632
#### \`allow-scripts-pin\`
4633+
#### \`dry-run\`
46284634
#### \`json\`
46294635
`
46304636

0 commit comments

Comments
 (0)