Skip to content

Commit cc17c4d

Browse files
committed
fix(path): harden root reads and store keys
1 parent 4696341 commit cc17c4d

19 files changed

Lines changed: 333 additions & 57 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@
1212

1313
- Route `Root.copyIn()` and overwrite-capable `Root.write()` commits through a new descriptor-relative native replace rename, closing a parent-symlink swap that could create a missing destination directory outside the root before the JavaScript fallback detected the escape. Native `auto` and `require` mode now protect both create-only and replacing pinned writes; the explicitly best-effort JavaScript fallback remains available in `off` mode or when `auto` cannot load a binding.
1414
- Report `not-found` rather than `invalid-path` or raw `ENOENT` when pinned `Root.write()` and `Root.copyIn()` calls cannot find their parent with `mkdir: false`, preserving the documented operational error category.
15+
- Reject stable intermediate symlinks in default `Root` reads and the sync/async root-file helpers, compare the pre-open path identity with the opened descriptor so an in-root parent swap reports `path-mismatch`, open reads nonblocking where supported so a raced FIFO cannot pin a worker, and report followed symlink loops with the documented `symlink` code.
16+
- Reject surrounding whitespace in every async and sync `FileStore` key instead of silently trimming one caller-supplied key onto another.
17+
- Keep Windows-ignored trailing spaces and dots from disguising reserved device basenames such as `CON .` in `sanitizeUntrustedFileName()` output.
18+
- Report overlong `Root` inputs as `invalid-path` instead of misclassifying the filesystem's `ENAMETOOLONG` failure as `outside-workspace`.
1519

1620
- Apply `movePathWithCopyFallback()` file and POSIX directory modes through staging descriptors before publication, so a replaceable staging pathname cannot redirect `chmod` to an unrelated symlink target. Windows no longer uses a pathname fallback for directory modes because Node cannot portably open a directory descriptor there and does not enforce POSIX modes.
1721

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ await using opened = await fs.openWritable("logs/current.log", { writeMode: "app
187187
}
188188
```
189189

190-
`nonBlockingRead` is the only I/O scheduling knob in `RootDefaults`; it applies to read/open operations because it changes how file descriptors are opened. Filesystem safety policy remains explicit through `hardlinks`, `symlinks`, and `denyMutations`.
190+
`nonBlockingRead` remains as a compatibility hint in `RootDefaults`. Safe read/open operations already use nonblocking descriptor opens where the platform supports them so a raced FIFO cannot pin a worker; filesystem safety policy remains explicit through `hardlinks`, `symlinks`, and `denyMutations`.
191191

192192
```ts
193193
const locked = await root("/srv/workspace", {

‎docs/advanced.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ Operational filesystem failures such as permissions or I/O errors are rethrown.
5656
| Export | Page | Notes |
5757
|---|---|---|
5858
| `readFileDescriptorBounded`, `readFileDescriptorBoundedSync`, `readFileHandleBounded` | – | Incremental whole-file reads for already-open descriptors/handles. They consume at most `maxBytes + 1`, do not close the input, and throw `FsSafeError("too-large")` on overflow. |
59-
| `openRootFile`, `openRootFileSync`, `canUseRootFileOpen`, `matchRootFileOpenFailure`, related types | – | Low-level no-follow open routed through the root-file path. |
59+
| `openRootFile`, `openRootFileSync`, `canUseRootFileOpen`, `matchRootFileOpenFailure`, related types | – | Low-level root-bounded open; rejects every symlink component by default, with `rejectSymlinks: false` for explicit in-root following. |
6060
| `appendRegularFile`, `appendRegularFileSync`, `readRegularFile`, `readRegularFileSync`, `statRegularFile`, `statRegularFileSync`, `resolveRegularFileAppendFlags`, `AppendRegularFileOptions`, `RegularFileStatResult` | [regular-file.md](regular-file.md) | Type-checked regular-file I/O. |
6161
| `sameFileIdentity`, `FileIdentityStat` | – | Compare two stats for same-inode equality. |
6262
| `pathExists`, `pathExistsSync` | – | Boolean existence check that does not throw on `ENOENT`. |

‎docs/file-store.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ as `C:name` (including an embedded segment such as `a/C:name`) throws
7070
`invalid-path` on every platform. This prevents a key created on POSIX from
7171
aliasing a different file when the store is moved to Windows. Colons elsewhere,
7272
such as the timestamp in `logs/2026-08-02T10:30:00Z.log`, remain valid.
73+
Keys with surrounding whitespace also throw `invalid-path`; the store never
74+
silently trims one caller-supplied key onto another key.
7375

7476
`root()` returns a [`Root`](root.md) handle for the same directory when you need the full surface (move, list, mkdir). It's a fresh handle per call and is safe to call frequently.
7577

‎docs/filename.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ In order:
2424
3. **Strip non-portable characters.** C0/C1 controls (`0x00`–`0x1f`, `0x7f`–`0x9f`) and the Windows-invalid set `< > : " / \\ | ? *` are removed on every platform.
2525
4. **Trim again.**
2626
5. If the result is empty, `"."`, or `".."`, return `fallbackName`.
27-
6. **Suffix Windows reserved basenames.** Compare the part before the first `.` case-insensitively with the Windows device-name set, including `CON`, `PRN`, `AUX`, `NUL`, `CLOCK$`, `CONIN$`, `CONOUT$`, `COM1..9`, `LPT1..9`, and their superscript `¹`, `²`, and `³` variants. A match gains `_` before its extension, preserving the original case and extension on every platform.
27+
6. **Suffix Windows reserved basenames.** Compare the part before the first `.` case-insensitively with the Windows device-name set, including `CON`, `PRN`, `AUX`, `NUL`, `CLOCK$`, `CONIN$`, `CONOUT$`, `COM1..9`, `LPT1..9`, and their superscript `¹`, `²`, and `³` variants. Windows-ignored spaces and dots at the end of that basename do not disguise a device name. A match gains `_` before its extension, preserving the original case and extension on every platform.
2828
7. **Truncate.** If the cleaned segment is longer than 200 characters, take the first 200.
2929

3030
That's it. The function stays intentionally small: it removes traversal and
@@ -53,9 +53,9 @@ sanitizeUntrustedFileName("a".repeat(300), "x"); // 200-char "aaa..."
5353
The function is deliberately narrow. It will not:
5454

5555
- Replace leading dots (so a name like `.config` stays hidden on POSIX systems).
56-
- Trim trailing dots or spaces. Windows normalizes those spellings, so names
57-
that differ only there can alias; reject or rewrite them when Windows
58-
portability or cross-platform store migration matters.
56+
- Trim trailing dots. Surrounding spaces are removed by the documented trim
57+
steps, but Windows-normalized dot/space spellings can still alias; reject or
58+
rewrite them when Windows portability or cross-platform migration matters.
5959
- Add an extension or change case.
6060
- Validate file *content*. To enforce an extension allow-list, check after sanitization.
6161
- Deduplicate against existing files. Append a random suffix if you need uniqueness.

‎docs/reading.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ Regardless of shape, every read goes through the same boundary checks:
2121
compatibility explicit for loader-style call sites.
2222
4. Reject known unsafe device and process-fd paths before opening (`device-path`).
2323
5. Open with `O_NOFOLLOW` where available. A symlink in the path triggers `symlink` unless the call's `symlinks` policy is `follow-within-root`.
24-
6. Stat the open fd and compare to the resolved path's identity (`sameFileIdentity`). A swap mid-call triggers `path-mismatch`.
24+
6. Compare the pre-open path identity, the open fd, and the post-open resolved path (`sameFileIdentity`). A swap mid-call triggers `path-mismatch`.
2525
7. If `hardlinks: "reject"`, refuse files with `nlink > 1` (`hardlink`).
2626
8. If `maxBytes` is set, refuse reads larger than the cap (`too-large`).
2727

@@ -86,14 +86,14 @@ try {
8686
type RootReadOptions = {
8787
hardlinks?: "reject" | "allow"; // override defaults.hardlinks
8888
maxBytes?: number; // refuse reads larger than this many bytes
89-
nonBlockingRead?: boolean; // schedule the read off the main loop
89+
nonBlockingRead?: boolean; // compatibility hint; safe opens are already nonblocking where supported
9090
symlinks?: "reject" | "follow-within-root"; // override defaults.symlinks
9191
};
9292
```
9393

9494
`maxBytes` is enforced eagerly: the library reads up to `maxBytes + 1` and throws `too-large` if there is more, so a hostile target cannot silently exhaust memory.
9595

96-
`nonBlockingRead` is a scheduling hint. It does not affect safety — it lets you keep the event loop responsive when reading large files.
96+
`nonBlockingRead` remains as a compatibility hint. Safe reads always add the platform's nonblocking open flag where available so a raced FIFO cannot pin a worker indefinitely; regular-file descriptor reads retain normal Node behavior.
9797

9898
## `readAbsolute()` and `reader()`
9999

‎docs/root.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ type RootDefaults = {
2323
maxBytes?: number; // refuse reads larger than this many bytes; defaults to 16 MiB
2424
mkdir?: boolean; // create missing parent dirs on write/openWritable/append; default true
2525
mode?: number; // file mode applied to new writes; per-call override available
26-
nonBlockingRead?: boolean; // schedule reads on a worker; useful for large files
26+
nonBlockingRead?: boolean; // compatibility hint; safe opens are already nonblocking where supported
2727
renameIdentity?: "strict" | "verify-content-with-lock"; // default "strict"
2828
symlinks?: "reject" | "follow-within-root"; // policy when a path component is a symlink
2929
};
@@ -84,6 +84,10 @@ await using opened = await fs.open("large.log");
8484
`containment: "best-effort"`. The field reports the mechanism used; see the
8585
[security model](security-model.md#containment-guarantees-by-platform).
8686
87+
The read methods also accept an absolute spelling that already resolves inside
88+
the root. `readAbsolute()` and `reader()` make that intent explicit; an absolute
89+
path outside the root is still rejected.
90+
8791
### Writes
8892
8993
```ts

‎docs/security-model.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ If you need full sandboxing, run the worker under reduced privileges (uid, conta
4545

4646
### Path traversal and absolute paths
4747

48-
Every relative path is resolved against the canonicalized real path of the root, then checked with `isPathInside`. Alias resolution walks components before applying a later `..`, so a symlink cannot change what that parent segment means after validation. Parent traversal that escapes, leading `/` (without `pathScope` opt-in), or any canonical result outside the root throws `outside-workspace`.
48+
Every path is resolved against the canonicalized real path of the root, then checked with `isPathInside`. Alias resolution walks components before applying a later `..`, so a symlink cannot change what that parent segment means after validation. Parent traversal, an absolute spelling, or any alias whose canonical result is outside the root throws `outside-workspace`; absolute spellings that remain inside the root are accepted.
4949

5050
### Symlinks (read side)
5151

‎src/file-store.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ export type FileStoreSync = {
108108

109109
function assertRelativePath(relativePath: string): string {
110110
const raw = relativePath.trim();
111-
if (!raw) {
112-
throw new FsSafeError("invalid-path", "relative path must be non-empty");
111+
if (!raw || raw !== relativePath) {
112+
throw new FsSafeError("invalid-path", "store key must be non-empty and unpadded");
113113
}
114114
return assertNoDriveRelativePathSegments(raw.replaceAll("\\", "/"), "store key");
115115
}

‎src/filename.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,24 @@ import { WINDOWS_RESERVED_DEVICE_NAMES } from "./device-path.js";
33

44
const WINDOWS_INVALID_FILE_NAME_CHARACTERS = new Set('<>:"/\\|?*');
55

6+
function trimWindowsIgnoredSuffix(value: string): string {
7+
let end = value.length;
8+
while (end > 0) {
9+
const character = value.charCodeAt(end - 1);
10+
if (character !== 0x20 && character !== 0x2e) {
11+
break;
12+
}
13+
end -= 1;
14+
}
15+
return end === value.length ? value : value.slice(0, end);
16+
}
17+
618
function suffixWindowsReservedDeviceName(fileName: string): string {
719
const extensionIndex = fileName.indexOf(".");
820
const baseNameEnd = extensionIndex < 0 ? fileName.length : extensionIndex;
921
const baseName = fileName.slice(0, baseNameEnd);
10-
if (!WINDOWS_RESERVED_DEVICE_NAMES.has(baseName.toUpperCase())) {
22+
const deviceBaseName = trimWindowsIgnoredSuffix(baseName);
23+
if (!WINDOWS_RESERVED_DEVICE_NAMES.has(deviceBaseName.toUpperCase())) {
1124
return fileName;
1225
}
1326
return `${baseName}_${fileName.slice(baseNameEnd)}`;

0 commit comments

Comments
 (0)