1
+/**
2
+ * Filename containment for untrusted input.
3
+ *
4
+ * Every field of an API response is untrusted, including filenames. When such a
5
+ * value becomes part of a filesystem path it must pass through this module
6
+ * first, and validation must happen before any `mkdir` or write so a rejected
7
+ * value leaves nothing behind on disk.
8
+ *
9
+ * TypeScript counterpart of `safe_basename` in `python/composio/utils/safe_path.py`.
10
+ * The two use the same validation order and whitespace rules. Path extraction
11
+ * is intentionally limited here; see `untrustedBasename`.
12
+ *
13
+ * Pure string logic with no filesystem access: no static `node:*` imports, so
14
+ * it is usable from edge/workerd builds.
15
+ */
16
+import { ValidationError } from '../errors/ValidationErrors';
17
+
18
+/**
19
+ * Upper bound on a filename, well under the 255-byte limit common to
20
+ * ext4/APFS/NTFS. Keeps a long server-supplied name from failing with a raw
21
+ * `ENAMETOOLONG` mid-write. Matches `MAX_COMPONENT_LENGTH` in the Python SDK.
22
+ */
23
+export const MAX_FILENAME_BYTES = 128;
24
+
25
+/**
26
+ * Reserved DOS device names. Writing to one on Windows targets the device
27
+ * rather than a file. Rejected on every platform so behavior does not diverge
28
+ * between a POSIX developer machine and a Windows deployment.
29
+ */
30
+const WINDOWS_RESERVED_NAMES: ReadonlySet<string> = new Set([
31
+ 'CON',
32
+ 'PRN',
33
+ 'AUX',
34
+ 'NUL',
35
+ ...Array.from({ length: 9 }, (_, i) => `COM${i + 1}`),
36
+ ...Array.from({ length: 9 }, (_, i) => `LPT${i + 1}`),
37
+ ...['¹', '²', '³'].flatMap(superscript => [`COM${superscript}`, `LPT${superscript}`]),
38
+]);
39
+
40
+/** Control characters and characters reserved by Windows. */
41
+const WINDOWS_INVALID_CHARS = /[\u0000-\u001f<>:"|?*]/;
42
+
43
+/**
44
+ * Python str.strip() whitespace: Unicode White_Space plus U+001C–U+001F.
45
+ * Unlike JavaScript trim(), this includes U+0085 and preserves U+FEFF.
46
+ */
47
+const PYTHON_WHITESPACE =
48
+ '[\\u0009-\\u000d\\u001c-\\u0020\\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
49
+const SURROUNDING_WHITESPACE = new RegExp(`^${PYTHON_WHITESPACE}+|${PYTHON_WHITESPACE}+$`, 'g');
50
+
51
+/**
52
+ * Returns the last path segment of `value`, treating both `/` and `\` as
53
+ * separators, or `''` when there is none.
54
+ *
55
+ * `path.basename()` on POSIX only splits on `/`, so a name crafted for a
56
+ * Windows target (`..\..\evil`) comes back intact on macOS and Linux. Splitting
57
+ * on both and removing an initial drive prefix also handles `C:report.txt`.
58
+ * This is not a full `PureWindowsPath` parser: dot components stay literal,
59
+ * and UNC anchors are not interpreted.
60
+ *
61
+ * Never throws: this is a display value as well as the input to
62
+ * {@link safeBasename}, and it is read while constructing download errors.
63
+ */
64
+export function untrustedBasename(value: string): string {
65
+ const segments = value.replace(/^[a-z]:/i, '').split(/[/\\]+/);
66
+ // Trailing separators name the same file: `a/b/` and `a/b` both basename to `b`.
67
+ while (segments.length > 0 && segments[segments.length - 1] === '') {
68
+ segments.pop();
69
+ }
70
+ return segments[segments.length - 1] ?? '';
71
+}
72
+
73
+/**
74
+ * True when `value` contains a surrogate code unit that is not part of a valid
75
+ * pair. Such a string cannot be encoded as UTF-8; `TextEncoder` silently
76
+ * substitutes U+FFFD, which would write a file under a name the response never
77
+ * specified. `String.prototype.isWellFormed()` is ES2024 and this package
78
+ * targets es2022, hence the manual scan.
79
+ */
80
+function hasLoneSurrogate(value: string): boolean {
81
+ for (let i = 0; i < value.length; i++) {
82
+ const code = value.charCodeAt(i);
83
+ if (code >= 0xd800 && code <= 0xdbff) {
84
+ const next = value.charCodeAt(i + 1);
85
+ if (!(next >= 0xdc00 && next <= 0xdfff)) {
86
+ return true;
87
+ }
88
+ i++;
89
+ } else if (code >= 0xdc00 && code <= 0xdfff) {
90
+ return true;
91
+ }
92
+ }
93
+ return false;
94
+}
95
+
96
+/**
97
+ * Collapses an untrusted filename to a bare, writable basename.
98
+ *
99
+ * Applies, in order: no usable basename (empty or a run of dots once
100
+ * surrounding whitespace is stripped), NUL bytes, control and Windows-reserved
101
+ * characters, trailing space or dot, invalid Unicode, a byte-length bound, and
102
+ * reserved device names. This is the order `safe_basename` uses in the Python
103
+ * SDK. This implementation rejects lone surrogates rather than relying on
104
+ * Python filesystem encoding behavior.
105
+ *
106
+ * Names that leave no usable basename are refused rather than replaced with a
107
+ * generated one: a response that cannot name its own file is malformed or
108
+ * hostile, and inventing a name would hide that. `""`, `"."` and `".."` make
109
+ * an output path equal to, or escape, its own directory, which surfaces as a
110
+ * raw `EISDIR` at write time instead of a validation error.
111
+ *
112
+ * The usability check runs on the *trimmed* basename because that is what gets
113
+ * written: Python-compatible stripping removes whitespace, so `"\u00a0.\u00a0"` would
114
+ * otherwise pass a check on the raw segment and then be written as `"."`. The
115
+ * hazard checks that follow run on the raw segment so a trailing ASCII space or
116
+ * dot is refused, not trimmed away. Check the stripped value for trailing dots
117
+ * too, since stripping whitespace can expose one.
118
+ *
119
+ * @param name - The untrusted filename or relative path to reduce.
120
+ * @param label - How the value is described in error messages.
121
+ * @returns The validated bare basename, with surrounding whitespace trimmed.
122
+ * @throws ValidationError if `name` yields no usable basename or is unsafe to write.
123
+ */
124
+export function safeBasename(name: string, label: string = 'filename'): string {
125
+ const rawBasename = untrustedBasename(name);
126
+ const basename = rawBasename.replace(SURROUNDING_WHITESPACE, '');
127
+
128
+ if (!basename || /^\.+$/.test(basename)) {
129
+ throw new ValidationError(
130
+ `Path traversal detected: ${label} ${JSON.stringify(name)} leaves no usable basename to write to.`
131
+ );
132
+ }
133
+ if (rawBasename.includes('\u0000')) {
134
+ throw new ValidationError(
135
+ `Refusing to write ${label} containing a NUL byte: ${JSON.stringify(name)}`
136
+ );
137
+ }
138
+ if (WINDOWS_INVALID_CHARS.test(rawBasename)) {
139
+ throw new ValidationError(
140
+ `Refusing to write ${label} containing characters reserved by Windows: ${JSON.stringify(name)}`
141
+ );
142
+ }
143
+ if (rawBasename.endsWith(' ') || rawBasename.endsWith('.') || basename.endsWith('.')) {
144
+ throw new ValidationError(
145
+ `Refusing to write ${label} ending in a space or dot: ${JSON.stringify(name)}`
146
+ );
147
+ }
148
+ if (hasLoneSurrogate(basename)) {
149
+ throw new ValidationError(
150
+ `Refusing to write ${label} containing invalid Unicode: ${JSON.stringify(name)}`
151
+ );
152
+ }
153
+
154
+ const encodedLength = new TextEncoder().encode(basename).length;
155
+ if (encodedLength > MAX_FILENAME_BYTES) {
156
+ throw new ValidationError(
157
+ `Refusing to write ${label} longer than ${MAX_FILENAME_BYTES} bytes: ` +
158
+ `${JSON.stringify(basename.slice(0, 32))}... (${encodedLength} bytes)`
159
+ );
160
+ }
161
+
162
+ // Compare everything before the first dot: on Windows `NUL.tar.gz` opens the
163
+ // null device just as `NUL` does, so extensions provide no protection.
164
+ const deviceName = basename.split('.', 1)[0].replace(/ +$/, '').toUpperCase();
165
+ if (WINDOWS_RESERVED_NAMES.has(deviceName)) {
166
+ throw new ValidationError(
167
+ `Refusing to write ${label} that is a reserved device name: ${JSON.stringify(name)}`
168
+ );
169
+ }
170
+
171
+ return basename;
172
+}