Skip to content

Commit 5ca756d

Browse files
committed
feat(filename): suffix Windows reserved names
1 parent 0965b89 commit 5ca756d

5 files changed

Lines changed: 79 additions & 12 deletions

File tree

‎CHANGELOG.md‎

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

33
## Unreleased
44

5+
### Features
6+
7+
- Suffix Windows reserved basenames with `_` in `sanitizeUntrustedFileName()` while preserving case and extensions on every platform, including dollar names and superscript COM/LPT variants; thanks @SebTardif (#67).
8+
59
## 0.5.1 - 2026-08-01
610

711
### Security and Correctness

‎docs/filename.md‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ 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. **Truncate.** If the cleaned segment is longer than 200 characters, take the first 200.
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.
28+
7. **Truncate.** If the cleaned segment is longer than 200 characters, take the first 200.
2829

2930
That's it. The function stays intentionally small: it produces one traversal-free segment whose characters work across the common POSIX and Windows filename surfaces.
3031

@@ -38,28 +39,24 @@ sanitizeUntrustedFileName("a\u0000b\tc", "upload"); // "abc"
3839
sanitizeUntrustedFileName(" ", "fallback"); // "fallback"
3940
sanitizeUntrustedFileName(".", "fallback"); // "fallback"
4041
sanitizeUntrustedFileName("..", "fallback"); // "fallback"
41-
sanitizeUntrustedFileName("a".repeat(300), "x"); // 200-char "aaa..."
42+
sanitizeUntrustedFileName("CON", "fallback"); // "CON_"
43+
sanitizeUntrustedFileName("nul.txt", "fallback"); // "nul_.txt"
44+
sanitizeUntrustedFileName("aux.c", "fallback"); // "aux_.c"
45+
sanitizeUntrustedFileName("conin$", "fallback"); // "conin$_"
46+
sanitizeUntrustedFileName("a".repeat(300), "x"); // 200-char "aaa..."
4247
```
4348

4449
## What it does **not** do
4550

4651
The function is deliberately narrow. It will not:
4752

48-
- Reject Windows reserved names (`CON`, `PRN`, `AUX`, `NUL`, `COM1..9`, `LPT1..9`).
4953
- Replace leading dots (so a name like `.config` stays hidden on POSIX systems).
5054
- Trim trailing dots or spaces (Windows tolerates them silently).
5155
- Add an extension or change case.
5256
- Validate file *content*. To enforce an extension allow-list, check after sanitization.
5357
- Deduplicate against existing files. Append a random suffix if you need uniqueness.
5458

55-
If your domain needs stricter handling, layer it on top:
56-
57-
```ts
58-
const trimmed = sanitizeUntrustedFileName(input, "upload");
59-
const noWindowsReserved = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..+)?$/i.test(trimmed)
60-
? "upload"
61-
: trimmed;
62-
```
59+
Windows reserved basenames are handled by the default portability pass; callers no longer need to layer a separate reserved-name recipe on top.
6360

6461
## Common patterns
6562

‎src/device-path.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ const POSIX_BLOCKED_DEVICE_PATHS = new Set([
2929
"/dev/console",
3030
]);
3131

32-
const WINDOWS_RESERVED_DEVICE_NAMES = new Set([
32+
export const WINDOWS_RESERVED_DEVICE_NAMES: ReadonlySet<string> = new Set([
3333
"CON",
3434
"PRN",
3535
"AUX",

‎src/filename.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
11
import path from "node:path";
2+
import { WINDOWS_RESERVED_DEVICE_NAMES } from "./device-path.js";
23

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

6+
function suffixWindowsReservedDeviceName(fileName: string): string {
7+
const extensionIndex = fileName.indexOf(".");
8+
const baseNameEnd = extensionIndex < 0 ? fileName.length : extensionIndex;
9+
const baseName = fileName.slice(0, baseNameEnd);
10+
if (!WINDOWS_RESERVED_DEVICE_NAMES.has(baseName.toUpperCase())) {
11+
return fileName;
12+
}
13+
return `${baseName}_${fileName.slice(baseNameEnd)}`;
14+
}
15+
516
export function sanitizeUntrustedFileName(fileName: string, fallbackName: string): string {
617
const trimmed = typeof fileName === "string" ? fileName.trim() : "";
718
if (!trimmed) {
@@ -25,6 +36,7 @@ export function sanitizeUntrustedFileName(fileName: string, fallbackName: string
2536
if (!base || base === "." || base === "..") {
2637
return fallbackName;
2738
}
39+
base = suffixWindowsReservedDeviceName(base);
2840
if (base.length > 200) {
2941
base = base.slice(0, 200);
3042
}

‎test/filename.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
import { describe, expect, it } from "vitest";
2+
import { WINDOWS_RESERVED_DEVICE_NAMES } from "../src/device-path.js";
23
import { sanitizeUntrustedFileName } from "../src/filename.js";
34

5+
function mixedCase(value: string): string {
6+
return Array.from(value, (character, index) =>
7+
index % 2 === 0 ? character : character.toLowerCase()
8+
).join("");
9+
}
10+
411
describe("sanitizeUntrustedFileName", () => {
512
it("keeps only the basename and strips control characters", () => {
613
expect(sanitizeUntrustedFileName("../nested/rep\u0000ort.pdf", "fallback.bin")).toBe(
@@ -9,13 +16,60 @@ describe("sanitizeUntrustedFileName", () => {
916
});
1017

1118
it("uses fallback for empty or path-alias names", () => {
19+
expect(sanitizeUntrustedFileName("", "fallback.bin")).toBe("fallback.bin");
1220
expect(sanitizeUntrustedFileName(" ", "fallback.bin")).toBe("fallback.bin");
21+
expect(sanitizeUntrustedFileName(".", "fallback.bin")).toBe("fallback.bin");
1322
expect(sanitizeUntrustedFileName("..", "fallback.bin")).toBe("fallback.bin");
23+
expect(sanitizeUntrustedFileName("<>", "fallback.bin")).toBe("fallback.bin");
1424
});
1525

1626
it("strips C1 controls and Windows-invalid characters on every platform", () => {
1727
expect(
1828
sanitizeUntrustedFileName('re<po>r:t"|?*\u0085\u009f.pdf', "fallback.bin"),
1929
).toBe("report.pdf");
2030
});
31+
32+
it.each([...WINDOWS_RESERVED_DEVICE_NAMES])(
33+
"suffixes reserved basename %s while preserving case and extensions",
34+
(reservedName) => {
35+
const casedName = mixedCase(reservedName);
36+
expect(sanitizeUntrustedFileName(reservedName, "fallback.bin")).toBe(
37+
`${reservedName}_`,
38+
);
39+
expect(sanitizeUntrustedFileName(`${reservedName}.txt`, "fallback.bin")).toBe(
40+
`${reservedName}_.txt`,
41+
);
42+
expect(sanitizeUntrustedFileName(casedName, "fallback.bin")).toBe(`${casedName}_`);
43+
expect(sanitizeUntrustedFileName(`${casedName}.TxT`, "fallback.bin")).toBe(
44+
`${casedName}_.TxT`,
45+
);
46+
},
47+
);
48+
49+
it("handles dollar names, superscript variants, and multi-part extensions", () => {
50+
expect(sanitizeUntrustedFileName("conin$", "fallback.bin")).toBe("conin$_");
51+
expect(sanitizeUntrustedFileName("ConOut$.log", "fallback.bin")).toBe(
52+
"ConOut$_.log",
53+
);
54+
expect(sanitizeUntrustedFileName("com¹.TXT", "fallback.bin")).toBe("com¹_.TXT");
55+
expect(sanitizeUntrustedFileName("LpT³.tar.gz", "fallback.bin")).toBe(
56+
"LpT³_.tar.gz",
57+
);
58+
});
59+
60+
it("suffixes reserved names before applying the 200-character limit", () => {
61+
const input = `CON.${"a".repeat(196)}`;
62+
const expected = `CON_.${"a".repeat(195)}`;
63+
expect(input).toHaveLength(200);
64+
expect(expected).toHaveLength(200);
65+
expect(sanitizeUntrustedFileName(input, "fallback.bin")).toBe(expected);
66+
});
67+
68+
it.each(["CON", "nul.txt", "CoNiN$.log", "COM¹.dat", "CON_"])(
69+
"is idempotent for reserved-name result %s",
70+
(input) => {
71+
const once = sanitizeUntrustedFileName(input, "fallback.bin");
72+
expect(sanitizeUntrustedFileName(once, "fallback.bin")).toBe(once);
73+
},
74+
);
2175
});

0 commit comments

Comments
 (0)