Skip to content

Commit 987aa0a

Browse files
authored
doc: add path rules and validation for export targets in package.json
PR-URL: #58604 Reviewed-By: Jacob Smith <jacob@frende.me> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent b23648e commit 987aa0a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

doc/api/packages.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,59 @@ subpaths where possible instead of a separate map entry per package subpath
433433
export. This also mirrors the requirement of using [the full specifier path][]
434434
in relative and absolute import specifiers.
435435

436+
#### Path Rules and Validation for Export Targets
437+
438+
When defining paths as targets in the [`"exports"`][] field, Node.js enforces
439+
several rules to ensure security, predictability, and proper encapsulation.
440+
Understanding these rules is crucial for authors publishing packages.
441+
442+
##### Targets must be relative URLs
443+
444+
All target paths in the [`"exports"`][] map (the values associated with export
445+
keys) must be relative URL strings starting with `./`.
446+
447+
```json
448+
// package.json
449+
{
450+
"name": "my-package",
451+
"exports": {
452+
".": "./dist/main.js", // Correct
453+
"./feature": "./lib/feature.js", // Correct
454+
// "./origin-relative": "/dist/main.js", // Incorrect: Must start with ./
455+
// "./absolute": "file:///dev/null", // Incorrect: Must start with ./
456+
// "./outside": "../common/util.js" // Incorrect: Must start with ./
457+
}
458+
}
459+
```
460+
461+
Reasons for this behavior include:
462+
463+
* **Security:** Prevents exporting arbitrary files from outside the
464+
package's own directory.
465+
* **Encapsulation:** Ensures all exported paths are resolved relative to
466+
the package root, making the package self-contained.
467+
468+
##### No path traversal or invalid segments
469+
470+
Export targets must not resolve to a location outside the package's root
471+
directory. Additionally, path segments like `.` (single dot), `..` (double dot),
472+
or `node_modules` (and their URL-encoded equivalents) are generally disallowed
473+
within the `target` string after the initial `./` and in any `subpath` part
474+
substituted into a target pattern.
475+
476+
```json
477+
// package.json
478+
{
479+
"name": "my-package",
480+
"exports": {
481+
// ".": "./dist/../../elsewhere/file.js", // Invalid: path traversal
482+
// ".": "././dist/main.js", // Invalid: contains "." segment
483+
// ".": "./dist/../dist/main.js", // Invalid: contains ".." segment
484+
// "./utils/./helper.js": "./utils/helper.js" // Key has invalid segment
485+
}
486+
}
487+
```
488+
436489
### Exports sugar
437490

438491
<!-- YAML

0 commit comments

Comments
 (0)