|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// A package.json that exists but cannot be read must not be treated as |
| 4 | +// absent. Doing so silently drops fields such as "exports", which can resolve |
| 5 | +// a specifier to a different file than the one the package declares. |
| 6 | +// Refs: https://github.com/nodejs/node/issues/65220 |
| 7 | + |
| 8 | +const common = require('../common'); |
| 9 | + |
| 10 | +if (common.isWindows) { |
| 11 | + common.skip('chmod does not restrict reads on Windows'); |
| 12 | +} |
| 13 | +if (process.getuid?.() === 0) { |
| 14 | + common.skip('cannot make a file unreadable as root'); |
| 15 | +} |
| 16 | + |
| 17 | +const assert = require('assert'); |
| 18 | +const fs = require('fs'); |
| 19 | +const path = require('path'); |
| 20 | +const { spawnSync } = require('child_process'); |
| 21 | +const tmpdir = require('../common/tmpdir'); |
| 22 | + |
| 23 | +tmpdir.refresh(); |
| 24 | + |
| 25 | +const depDir = tmpdir.resolve('node_modules/dep'); |
| 26 | +fs.mkdirSync(path.join(depDir, 'lib'), { recursive: true }); |
| 27 | +const depPackageJson = path.join(depDir, 'package.json'); |
| 28 | +fs.writeFileSync( |
| 29 | + depPackageJson, |
| 30 | + '{"name":"dep","exports":{".":"./lib/real.js"}}', |
| 31 | +); |
| 32 | +fs.writeFileSync(path.join(depDir, 'lib', 'real.js'), 'export const which = "real";'); |
| 33 | +// If the package config is ignored, resolution falls back to this file. |
| 34 | +fs.writeFileSync(path.join(depDir, 'index.js'), 'export const which = "decoy";'); |
| 35 | + |
| 36 | +fs.writeFileSync(tmpdir.resolve('package.json'), '{"type":"module"}'); |
| 37 | +const entry = tmpdir.resolve('main.mjs'); |
| 38 | +fs.writeFileSync(entry, 'import { which } from "dep"; console.log(which);'); |
| 39 | + |
| 40 | +// Sanity check: the export resolves while the package config is readable. |
| 41 | +{ |
| 42 | + const child = spawnSync(process.execPath, [entry], { encoding: 'utf8' }); |
| 43 | + assert.strictEqual(child.stdout.trim(), 'real'); |
| 44 | + assert.strictEqual(child.status, 0, child.stderr); |
| 45 | +} |
| 46 | + |
| 47 | +fs.chmodSync(depPackageJson, 0o000); |
| 48 | + |
| 49 | +try { |
| 50 | + const child = spawnSync(process.execPath, [entry], { encoding: 'utf8' }); |
| 51 | + // The read failure must be reported rather than resolving to index.js. |
| 52 | + assert.doesNotMatch(child.stdout, /decoy/); |
| 53 | + assert.match(child.stderr, /Cannot read package config/); |
| 54 | + assert.notStrictEqual(child.status, 0); |
| 55 | +} finally { |
| 56 | + fs.chmodSync(depPackageJson, 0o644); |
| 57 | +} |
0 commit comments