MediumPro challengeJavaScriptTypeScript

Sanitize File Path

Node.jsSecurityFiles

The function below builds a file path by concatenating a base directory with user-supplied input.

The bug: an attacker can pass "../../../etc/passwd" as the filename and read any file on the server — a classic path traversal (directory traversal) attack.

Your task: fix solve(basePath, userInput) so that:

  • Valid filenames within the base directory return the full path.
  • Any input that would escape basePath returns null.
  • Use string operations only (no require('path') available in this sandbox).
solve('/uploads', 'photo.jpg')        // → '/uploads/photo.jpg'
solve('/uploads', 'sub/image.png')    // → '/uploads/sub/image.png'
solve('/uploads', '../etc/passwd')    // → null
solve('/uploads', '../../secret.key') // → null

Sample tests

Test #1Subdirectory — allowed
Input: ["/uploads","sub/image.png"]
Output: "/uploads/sub/image.png"
Test #2Normal file — allowed
Input: ["/uploads","photo.jpg"]
Output: "/uploads/photo.jpg"
Test #3One level up — blocked
Input: ["/uploads","../etc/passwd"]
Output: null
Test #4Two levels up — blocked
Input: ["/uploads","../../secret.key"]
Output: null