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