Skip to content

Commit b317f16

Browse files
fix: write registry allowScripts keys under install-strategy=linked (#9941)
Under `install-strategy=linked`, `npm install-scripts approve <pkg>` wrote verbose, duplicated `file:` entries pointing into `node_modules/.store` (one per incoming symlink depth) instead of `name@version` pins, and those store-path entries never matched at install time. There are two root causes. In `findNodesForArgs` (allow-scripts-cmd.js), positional args matched every `Link` pointing at the store package; each Link's relative `file:.store/...` resolved spec became its own policy key and could even strip the correct pin as stale. In `script-allowed.js`, a store package has no `edgesIn` (they land on its incoming Links), so `isRegistryNode` refused registry keys, and `ls`, the post-install advisory, and prune treated a correct `name@version` entry as matching nothing. The fix skips `Link` nodes when matching positional args, mirroring `collectUnreviewedScripts` and prune, so approvals key off the real package's trusted registry identity. `isRegistryNode` and `nameFromEdges` now delegate edge-based checks to a link target's incoming Links, which also covers `omit-lockfile-registry-resolved` (approve by name, like the hoisted #9558 path). `resolvedSourceSpecs` no longer fabricates `file:` specs from links into the store, so store packages are never keyed by store paths and prune cleans up the buggy entries while keeping the valid pin. ## References Fixes #9939
1 parent c276cad commit b317f16

6 files changed

Lines changed: 575 additions & 11 deletions

File tree

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

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -221,25 +221,27 @@ class AllowScriptsCmd extends BaseCommand {
221221
// edge name. A version or range on the arg narrows the match to installed
222222
// versions that satisfy it. Bundled deps are excluded for the same reason
223223
// as --all. Args that match nothing are returned in `unmatched`.
224+
// Links stay matchable by their edge name (e.g. `foo` -> `file:./local-foo`), but each match is dereferenced to its target and deduplicated, since scripts only run on the target and keying policy off a Link's resolved spec writes store paths under install-strategy=linked (npm/cli#9939).
224225
const matched = []
225226
const unmatched = []
226227
for (const arg of args) {
227228
const { name: wantName, range } = parsePositional(arg)
228-
const found = []
229+
const found = new Set()
229230
for (const node of arb.actualTree.inventory.values()) {
230-
if (node.isProjectRoot || node.isWorkspace || node.inBundle) {
231-
continue
232-
}
233231
const { name, version } = trustedDisplay(node)
234232
if (!name || name !== wantName) {
235233
continue
236234
}
237235
if (range && (!version || !semver.satisfies(version, range, { loose: true }))) {
238236
continue
239237
}
240-
found.push(node)
238+
const target = node.isLink ? node.target : node
239+
if (!target || target.isProjectRoot || target.isWorkspace || target.inBundle) {
240+
continue
241+
}
242+
found.add(target)
241243
}
242-
if (found.length === 0) {
244+
if (found.size === 0) {
243245
unmatched.push(arg)
244246
} else {
245247
matched.push(...found)

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ const classifyUnusedEntries = (allowScripts, nodes) => {
2929
continue
3030
}
3131

32-
const matching = nodes.filter(({ node }) => matches(node, key))
32+
// Pass deny intent so an unverifiable version fails closed: an active versioned deny must not be classified as unused while its broad allow survives.
33+
const matching = nodes.filter(({ node }) => matches(node, key, value === false))
3334
if (matching.length === 0) {
3435
removed.push({ key, value, reason: 'not-installed' })
3536
continue

‎test/lib/commands/approve-scripts.js‎

Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -859,3 +859,250 @@ t.test('approve-scripts --all with only bundled deps has nothing to review', asy
859859
const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8'))
860860
t.notOk(pkg.allowScripts, 'no allowScripts written')
861861
})
862+
863+
// Layout produced by install-strategy=linked: the real package lives in the store, node_modules holds a symlink to it, and the hidden lockfile records that isolated layout (npm/cli#9939).
864+
const setupLinkedProject = (t, { allowScripts, noResolved = false } = {}) => {
865+
const storeDir = '[email protected]'
866+
const storeLoc = `node_modules/.store/${storeDir}/node_modules/canvas`
867+
const tarUrl = noResolved
868+
? undefined
869+
: 'https://registry.npmjs.org/canvas/-/canvas-1.0.0.tgz'
870+
const pkg = {
871+
name: 'host',
872+
version: '1.0.0',
873+
dependencies: { canvas: '^1.0.0' },
874+
}
875+
if (allowScripts !== undefined) {
876+
pkg.allowScripts = allowScripts
877+
}
878+
return {
879+
'package.json': JSON.stringify(pkg, null, 2),
880+
'package-lock.json': JSON.stringify({
881+
name: pkg.name,
882+
version: pkg.version,
883+
lockfileVersion: 3,
884+
requires: true,
885+
packages: {
886+
'': pkg,
887+
'node_modules/canvas': {
888+
version: '1.0.0',
889+
resolved: tarUrl,
890+
hasInstallScript: true,
891+
},
892+
},
893+
}),
894+
node_modules: {
895+
'.package-lock.json': JSON.stringify({
896+
lockfileVersion: 3,
897+
requires: true,
898+
packages: {
899+
[`node_modules/.store/${storeDir}`]: {},
900+
[storeLoc]: {
901+
version: '1.0.0',
902+
resolved: tarUrl,
903+
hasInstallScript: true,
904+
},
905+
'node_modules/canvas': {
906+
resolved: storeLoc,
907+
link: true,
908+
},
909+
},
910+
}),
911+
'.store': {
912+
[storeDir]: {
913+
node_modules: {
914+
canvas: {
915+
'package.json': JSON.stringify({
916+
name: 'canvas',
917+
version: '1.0.0',
918+
scripts: { install: 'echo install' },
919+
}),
920+
},
921+
},
922+
},
923+
},
924+
canvas: t.fixture('symlink', `.store/${storeDir}/node_modules/canvas`),
925+
},
926+
}
927+
}
928+
929+
// loadActual only trusts the hidden lockfile when it is newer than every dir under node_modules (assertNoNewer allows 10ms), and fixture creation order makes that racy, so bump its mtime past the fixture writes.
930+
const trustHiddenLockfile = (prefix) => {
931+
const future = new Date(Date.now() + 60_000)
932+
fs.utimesSync(resolve(prefix, 'node_modules', '.package-lock.json'), future, future)
933+
}
934+
935+
t.test('approve-scripts <pkg> under linked strategy writes a registry pin, not store paths', async t => {
936+
const { npm, prefix } = await mockNpm(t, {
937+
prefixDir: setupLinkedProject(t),
938+
})
939+
trustHiddenLockfile(prefix)
940+
await npm.exec('approve-scripts', ['canvas'])
941+
942+
const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8'))
943+
t.strictSame(pkg.allowScripts, { '[email protected]': true })
944+
})
945+
946+
t.test('approve-scripts --all under linked strategy writes a registry pin, not store paths', async t => {
947+
const { npm, prefix } = await mockNpm(t, {
948+
prefixDir: setupLinkedProject(t),
949+
config: { all: true },
950+
})
951+
trustHiddenLockfile(prefix)
952+
await npm.exec('approve-scripts', [])
953+
954+
const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8'))
955+
t.strictSame(pkg.allowScripts, { '[email protected]': true })
956+
})
957+
958+
t.test('approve-scripts --pending is empty when the registry pin covers a linked store package', async t => {
959+
const { npm, prefix, joinedOutput } = await mockNpm(t, {
960+
prefixDir: setupLinkedProject(t, { allowScripts: { '[email protected]': true } }),
961+
config: { 'allow-scripts-pending': true },
962+
})
963+
trustHiddenLockfile(prefix)
964+
await npm.exec('approve-scripts', [])
965+
t.match(joinedOutput(), /No packages with unreviewed install scripts/)
966+
})
967+
968+
t.test('deny-scripts under linked strategy writes a name-only deny', async t => {
969+
const { npm, prefix } = await mockNpm(t, {
970+
prefixDir: setupLinkedProject(t),
971+
})
972+
trustHiddenLockfile(prefix)
973+
await npm.exec('deny-scripts', ['canvas'])
974+
975+
const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8'))
976+
t.strictSame(pkg.allowScripts, { canvas: false })
977+
})
978+
979+
const setupLocalFileDepProject = (t) => {
980+
const pkg = {
981+
name: 'host',
982+
version: '1.0.0',
983+
dependencies: { foo: 'file:./local-foo' },
984+
}
985+
return {
986+
'package.json': JSON.stringify(pkg, null, 2),
987+
'package-lock.json': JSON.stringify({
988+
name: 'host',
989+
version: '1.0.0',
990+
lockfileVersion: 3,
991+
requires: true,
992+
packages: {
993+
'': pkg,
994+
'local-foo': {
995+
name: 'local-foo',
996+
version: '1.0.0',
997+
hasInstallScript: true,
998+
},
999+
'node_modules/foo': {
1000+
resolved: 'local-foo',
1001+
link: true,
1002+
},
1003+
},
1004+
}),
1005+
'local-foo': {
1006+
'package.json': JSON.stringify({
1007+
name: 'local-foo',
1008+
version: '1.0.0',
1009+
scripts: { install: 'echo install' },
1010+
}),
1011+
},
1012+
node_modules: {
1013+
foo: t.fixture('symlink', '../local-foo'),
1014+
},
1015+
}
1016+
}
1017+
1018+
t.test('approve-scripts <name> finds a local file: dep through its link', async t => {
1019+
// The Link is named `foo` while its target is named `local-foo`; positional matching must dereference the Link instead of skipping it (npm/cli#9939 review).
1020+
const { npm, prefix } = await mockNpm(t, {
1021+
prefixDir: setupLocalFileDepProject(t),
1022+
})
1023+
await npm.exec('approve-scripts', ['foo'])
1024+
1025+
const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8'))
1026+
t.strictSame(pkg.allowScripts, { 'file:../local-foo': true })
1027+
})
1028+
1029+
t.test('deny-scripts <name> finds a local file: dep through its link', async t => {
1030+
const { npm, prefix } = await mockNpm(t, {
1031+
prefixDir: setupLocalFileDepProject(t),
1032+
})
1033+
await npm.exec('deny-scripts', ['foo'])
1034+
1035+
const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8'))
1036+
t.strictSame(pkg.allowScripts, { 'file:../local-foo': false })
1037+
})
1038+
1039+
t.test('approve-scripts <pkg> under linked strategy without resolved URLs approves by name', async t => {
1040+
// omit-lockfile-registry-resolved: the store package has no resolved URL, so it cannot be pinned but must still be approved by name via the incoming Link's edge.
1041+
const { npm, prefix } = await mockNpm(t, {
1042+
prefixDir: setupLinkedProject(t, { noResolved: true }),
1043+
})
1044+
trustHiddenLockfile(prefix)
1045+
await npm.exec('approve-scripts', ['canvas'])
1046+
1047+
const pkg = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8'))
1048+
t.strictSame(pkg.allowScripts, { canvas: true })
1049+
})
1050+
1051+
for (const state of ['missing', 'stale']) {
1052+
t.test(`prune keeps denies with a ${state} hidden lockfile`, async t => {
1053+
// With no trusted version, the versioned deny still blocks at runtime, so prune must fail closed and keep it instead of flipping the effective policy to allowed (npm/cli#9941 review).
1054+
const Arborist = require('@npmcli/arborist')
1055+
const isScriptAllowed = require('@npmcli/arborist/lib/script-allowed.js')
1056+
const allowScripts = {
1057+
canvas: true,
1058+
1059+
}
1060+
1061+
const { npm, prefix } = await mockNpm(t, {
1062+
prefixDir: setupLinkedProject(t, { allowScripts }),
1063+
config: { 'install-strategy': 'linked' },
1064+
})
1065+
1066+
const hidden = resolve(prefix, 'node_modules', '.package-lock.json')
1067+
if (state === 'missing') {
1068+
fs.unlinkSync(hidden)
1069+
} else {
1070+
fs.utimesSync(hidden, new Date(0), new Date(0))
1071+
}
1072+
1073+
t.equal(npm.config.get('omit-lockfile-registry-resolved'), false)
1074+
1075+
const arb = new Arborist({ ...npm.flatOptions, path: prefix })
1076+
const tree = await arb.loadActual()
1077+
const target = [...tree.inventory.values()]
1078+
.find(node => !node.isLink && node.name === 'canvas')
1079+
1080+
t.ok(target, 'finds the installed target')
1081+
t.strictSame(
1082+
isScriptAllowed.getTrustedRegistryIdentity(target),
1083+
{ name: 'canvas', version: null },
1084+
'recovers the registry name without inventing a trusted version'
1085+
)
1086+
t.equal(
1087+
isScriptAllowed(target, allowScripts),
1088+
false,
1089+
'the versioned deny blocks the package before pruning'
1090+
)
1091+
1092+
await npm.exec('install-scripts', ['prune'])
1093+
1094+
const pkg = JSON.parse(
1095+
fs.readFileSync(resolve(prefix, 'package.json'), 'utf8')
1096+
)
1097+
t.strictSame(
1098+
pkg.allowScripts,
1099+
allowScripts,
1100+
'pruning preserves both the allow and its active deny exception'
1101+
)
1102+
t.equal(
1103+
isScriptAllowed(target, pkg.allowScripts),
1104+
false,
1105+
'the package remains denied after pruning'
1106+
)
1107+
})
1108+
}

‎test/lib/commands/install-scripts.js‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,3 +334,64 @@ t.test('install-scripts prune fails for global installs', async t => {
334334
{ code: 'EGLOBAL' }
335335
)
336336
})
337+
338+
t.test('install-scripts prune under linked strategy keeps the registry pin, drops store paths', async t => {
339+
// Regression for npm/cli#9939: the buggy writer produced file:.store keys; prune must drop those and keep the valid registry pin covering the store package.
340+
const storeDir = '[email protected]'
341+
const storeLoc = `node_modules/.store/${storeDir}/node_modules/canvas`
342+
const tarUrl = 'https://registry.npmjs.org/canvas/-/canvas-1.0.0.tgz'
343+
const pkg = {
344+
name: 'host',
345+
version: '1.0.0',
346+
dependencies: { canvas: '^1.0.0' },
347+
allowScripts: {
348+
349+
[`file:.store/${storeDir}/node_modules/canvas`]: true,
350+
},
351+
}
352+
const { npm, prefix, joinedOutput } = await mockNpm(t, {
353+
prefixDir: {
354+
'package.json': JSON.stringify(pkg, null, 2),
355+
node_modules: {
356+
'.package-lock.json': JSON.stringify({
357+
lockfileVersion: 3,
358+
requires: true,
359+
packages: {
360+
[`node_modules/.store/${storeDir}`]: {},
361+
[storeLoc]: {
362+
version: '1.0.0',
363+
resolved: tarUrl,
364+
hasInstallScript: true,
365+
},
366+
'node_modules/canvas': {
367+
resolved: storeLoc,
368+
link: true,
369+
},
370+
},
371+
}),
372+
'.store': {
373+
[storeDir]: {
374+
node_modules: {
375+
canvas: {
376+
'package.json': JSON.stringify({
377+
name: 'canvas',
378+
version: '1.0.0',
379+
scripts: { install: 'echo install' },
380+
}),
381+
},
382+
},
383+
},
384+
},
385+
canvas: t.fixture('symlink', `.store/${storeDir}/node_modules/canvas`),
386+
},
387+
},
388+
})
389+
// loadActual only trusts the hidden lockfile when it is newer than every dir under node_modules (assertNoNewer allows 10ms), and fixture creation order makes that racy, so bump its mtime past the fixture writes.
390+
const future = new Date(Date.now() + 60_000)
391+
fs.utimesSync(resolve(prefix, 'node_modules', '.package-lock.json'), future, future)
392+
await npm.exec('install-scripts', ['prune'])
393+
394+
const updated = JSON.parse(fs.readFileSync(resolve(prefix, 'package.json'), 'utf8'))
395+
t.strictSame(updated.allowScripts, { '[email protected]': true })
396+
t.match(joinedOutput(), /file:\.store.*\(package not installed\)/)
397+
})

0 commit comments

Comments
 (0)