* Sanitize a file path key by rejecting dangerous patterns. * Checks for null bytes, URL-encoded traversals, and other injection vectors. * Returns the sanitized string or throws PathTraversalError.
(key: string)
| 22 | * Returns the sanitized string or throws PathTraversalError. |
| 23 | */ |
| 24 | function sanitizePathKey(key: string): string { |
| 25 | // Null bytes can truncate paths in C-based syscalls |
| 26 | if (key.includes('\0')) { |
| 27 | throw new PathTraversalError(`Null byte in path key: "${key}"`) |
| 28 | } |
| 29 | // URL-encoded traversals (e.g. %2e%2e%2f = ../) |
| 30 | let decoded: string |
| 31 | try { |
| 32 | decoded = decodeURIComponent(key) |
| 33 | } catch { |
| 34 | // Malformed percent-encoding (e.g. %ZZ, lone %) — not valid URL-encoding, |
| 35 | // so no URL-encoded traversal is possible |
| 36 | decoded = key |
| 37 | } |
| 38 | if (decoded !== key && (decoded.includes('..') || decoded.includes('/'))) { |
| 39 | throw new PathTraversalError(`URL-encoded traversal in path key: "${key}"`) |
| 40 | } |
| 41 | // Unicode normalization attacks: fullwidth ../ (U+FF0E U+FF0F) normalize |
| 42 | // to ASCII ../ under NFKC. While path.resolve/fs.writeFile treat these as |
| 43 | // literal bytes (not separators), downstream layers or filesystems may |
| 44 | // normalize — reject for defense-in-depth (PSR M22187 vector 4). |
| 45 | const normalized = key.normalize('NFKC') |
| 46 | if ( |
| 47 | normalized !== key && |
| 48 | (normalized.includes('..') || |
| 49 | normalized.includes('/') || |
| 50 | normalized.includes('\\') || |
| 51 | normalized.includes('\0')) |
| 52 | ) { |
| 53 | throw new PathTraversalError( |
| 54 | `Unicode-normalized traversal in path key: "${key}"`, |
| 55 | ) |
| 56 | } |
| 57 | // Reject backslashes (Windows path separator used as traversal vector) |
| 58 | if (key.includes('\\')) { |
| 59 | throw new PathTraversalError(`Backslash in path key: "${key}"`) |
| 60 | } |
| 61 | // Reject absolute paths |
| 62 | if (key.startsWith('/')) { |
| 63 | throw new PathTraversalError(`Absolute path key: "${key}"`) |
| 64 | } |
| 65 | return key |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Whether team memory features are enabled. |
no outgoing calls
no test coverage detected