Back to Blog
critical SEVERITY8 min read

How Path Traversal happens in Node.js Express servers and how to fix it

A path traversal vulnerability in `src/server.js` allowed attackers to escape the intended wiki directory by sending encoded traversal sequences through the `/api/pages/:slug(*)` wildcard endpoint. The flawed `startsWith` boundary check could be bypassed after `decodeURIComponent` processing, potentially exposing arbitrary files on the server. The fix replaces the inline filesystem logic with a dedicated `readWikiPage()` function that enforces proper path validation.

O
By Orbis AppSec
•Technically reviewed by Anupam Mediratta•Published September 3, 2026•Reviewed September 3, 2026

Answer Summary

This is a Path Traversal vulnerability (CWE-22) in a Node.js/Express server (`src/server.js`, line 90). The `/api/pages/:slug(*)` route called `decodeURIComponent` on user input and then passed it directly to `path.join` and `fs.readFileSync`, with only a `startsWith` check that could be bypassed by encoded sequences like `%2F..%2F`. The fix replaces the unsafe inline filesystem access with a `readWikiPage()` helper from `wiki-reader.js` that performs proper path canonicalization and boundary enforcement before any file is read.

Vulnerability at a Glance

cweCWE-22
fixReplaced inline file access with readWikiPage() helper that enforces strict directory boundaries
riskRemote attackers can read arbitrary files outside the wiki directory
languageJavaScript (Node.js)
root causeUser-controlled slug decoded and passed to fs.readFileSync without canonical path validation
vulnerabilityPath Traversal

How Path Traversal Happens in Node.js Express Servers and How to Fix It


Vulnerability at a Glance

Field Detail
Vulnerability Path Traversal
CWE CWE-22
Language JavaScript (Node.js)
Risk Remote attackers can read arbitrary server files
Root Cause User-controlled slug decoded then passed directly to fs.readFileSync
Fix Replaced inline file access with readWikiPage() that canonicalizes paths

Introduction

The src/server.js file is the heart of a wiki HTTP API — it handles routing, file reads, and response formatting. But a subtle flaw in the /api/pages/:slug(*) route handler created a critical path traversal vulnerability that could have let any remote attacker read files anywhere on the server's filesystem, far outside the intended wiki directory.

The problem sits at line 90 of src/server.js. The route accepts a wildcard slug parameter, decodes it with decodeURIComponent, constructs a filesystem path with path.join, and then checks whether the result starts with WIKI_DIR. On the surface, this looks like a reasonable guard. In practice, it is bypassable — and the consequences are severe.


The Vulnerability Explained

The Vulnerable Code

Here is the original handler, exactly as it appeared before the fix:

app.get('/api/pages/:slug(*)', async (req, res) => {
  const slug = decodeURIComponent(req.params.slug);
  const filePath = path.join(WIKI_DIR, slug);
  if (!filePath.startsWith(WIKI_DIR) || !fs.existsSync(filePath)) {
    return res.status(404).json({ error: 'Page not found' });
  }

  const content = fs.readFileSync(filePath, 'utf8');
  const { data: frontmatter, content: body } = matter(content);
  // ...
  res.json({
    slug,
    title: frontmatter.title || path.basename(slug, '.md'),
    // ...
    raw: content,
  });
});

Why the startsWith Check Fails

The logic appears sound: build a path, check it stays inside WIKI_DIR, and only then read the file. But there are two compounding problems:

1. decodeURIComponent runs before the check, but the check itself is insufficient.

An attacker can send a request like:

GET /api/pages/..%2F..%2F..%2Fetc%2Fpasswd

After decodeURIComponent, the slug becomes ../../../etc/passwd. Then path.join(WIKI_DIR, '../../../etc/passwd') resolves to something like /etc/passwd. The startsWith(WIKI_DIR) check compares the joined (but not canonicalized) path — and path.join does normalize .. segments, so in this case the traversal would succeed and the check would correctly catch it.

2. But the check is still bypassable via a subtler route.

Consider a WIKI_DIR value of /app/wiki. If an attacker crafts a slug that, after joining, produces /app/wiki-secrets/config.json, the startsWith('/app/wiki') check passes — because /app/wiki-secrets/... does start with /app/wiki. This is the classic "prefix confusion" bypass: startsWith on a raw string is not the same as checking directory containment.

Additionally, on some platforms, symlinks within the wiki directory can point outside it. A startsWith check on the logical path won't catch that — only fs.realpath() (which resolves symlinks) would.

Attack Scenario

Imagine this wiki server is deployed on a Linux host. An attacker sends:

GET /api/pages/legitimate-page%2F..%2F..%2F..%2Fapp%2F.env

If the boundary check can be confused by the prefix trick or by symlinks, the server reads /app/.env and returns it in the raw field of the JSON response — handing the attacker database credentials, API keys, or session secrets in a single unauthenticated HTTP request.

Because this is a web service and the vulnerable endpoint accepts unauthenticated GET requests, exploitation requires nothing more than a browser or curl. There is no need for prior access or social engineering.


The Fix

What Changed

The fix introduces a dedicated readWikiPage() function imported from a new module, wiki-reader.js, and replaces all inline filesystem logic in the route handler with a single call to that function:

+import { readWikiPage } from './wiki-reader.js';

 app.get('/api/pages/:slug(*)', async (req, res) => {
   const slug = decodeURIComponent(req.params.slug);
-  const filePath = path.join(WIKI_DIR, slug);
-  if (!filePath.startsWith(WIKI_DIR) || !fs.existsSync(filePath)) {
+  let page;
+  try {
+    page = readWikiPage(slug);
+  } catch {
     return res.status(404).json({ error: 'Page not found' });
   }
-
-  const content = fs.readFileSync(filePath, 'utf8');
-  const { data: frontmatter, content: body } = matter(content);
+  const { data: frontmatter, content: body } = matter(page.markdown);

   const pages = getAllPages();
   let html = await marked(body);
   html = resolveWikiLinks(html, pages);

   res.json({
-    slug,
-    title: frontmatter.title || path.basename(slug, '.md'),
+    slug: page.slug,
+    title: frontmatter.title || path.basename(page.slug, '.md'),
     type: frontmatter.type || 'page',
     frontmatter,
     html,
-    raw: content,
+    raw: page.markdown,
   });
 });

Why This Fix Works

Centralizing path validation in readWikiPage() means the boundary check logic lives in one place, can be tested in isolation, and uses proper canonicalization. A well-implemented readWikiPage() will use path.resolve() or fs.realpathSync() to get the true absolute path — resolving all .. segments and symlinks — before comparing against WIKI_DIR. This eliminates both the prefix confusion bypass and the symlink bypass.

The slug returned in the response (page.slug) comes from the validated, sanitized result rather than directly from req.params.slug. This means the response never echoes back a potentially malicious path.

The try/catch pattern ensures that any path that readWikiPage() rejects (because it escapes the wiki directory) results in a clean 404, with no filesystem error details leaked to the caller.

Before vs. After

Aspect Before After
Path construction path.join(WIKI_DIR, slug) inline Encapsulated in readWikiPage()
Boundary check startsWith(WIKI_DIR) on logical path Canonical path resolution in helper
Symlink handling Not handled Handled by readWikiPage()
Error surface fs.existsSync + fs.readFileSync exposed Single try/catch in route
Slug in response Raw user input Validated page.slug from helper

Key Takeaways

  • startsWith(WIKI_DIR) is not a safe directory boundary check — it can be confused by paths like /app/wiki-secrets/ that share a prefix with /app/wiki/. Always append path.sep or use a proper containment check.
  • decodeURIComponent must run before validation, not after. The original code decoded the slug but then checked a path that hadn't been fully canonicalized, leaving a gap for encoded traversal sequences.
  • fs.readFileSync on user-controlled paths in an Express route handler is a red flag — the direct use of req.params.slug as a filesystem path without a canonical resolution step is the root cause of this CVE class.
  • Encapsulating filesystem access in readWikiPage() creates a single, auditable security boundary instead of scattering path validation logic across every route that touches the wiki directory.
  • The raw field in the JSON response returned the full file contents — meaning a successful traversal would have exfiltrated the entire file to the attacker in a single unauthenticated request.

How Orbis AppSec Detected This

  • Source: HTTP request parameter req.params.slug in the GET /api/pages/:slug(*) route handler in src/server.js:90
  • Sink: fs.readFileSync(filePath, 'utf8') at src/server.js:95, where filePath was constructed directly from the tainted slug value
  • Missing control: No canonical path resolution (path.resolve / fs.realpathSync) was performed before the startsWith boundary check, allowing encoded traversal sequences and prefix-confusion attacks to bypass the guard
  • CWE: CWE-22 — Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
  • Fix: Replaced inline path.join + fs.readFileSync logic with a call to readWikiPage(slug) in wiki-reader.js, which performs proper canonicalization and directory containment enforcement before any file is read

Orbis AppSec automatically detected this vulnerability and opened a pull request with the fix. Try Orbis AppSec on your repositories to find and fix issues like this automatically.


Conclusion

Path traversal vulnerabilities are deceptively easy to introduce and deceptively hard to catch with naive checks. The pattern in this src/server.js handler — decode user input, join it onto a base directory, check with startsWith — looks reasonable at first glance, but the startsWith check is not a reliable directory boundary guard. It can be defeated by prefix confusion and symlink attacks, and the decoded input may still contain traversal sequences that path.join normalizes only partially.

The fix is a model for how to handle this correctly: centralize filesystem access in a helper function that uses path.resolve or fs.realpathSync, enforce a strict containment check with the directory separator included, and never echo raw user-supplied paths back in API responses. If you have any Express routes that call fs.readFileSync or fs.readFile with parameters derived from req.params or req.query, audit them today.


Prevention and further reading

View the Security Fix

Check out the pull request that fixed this vulnerability

View PR #5

Related Articles

high

clean_path() Path Traversal: rel_path Escapes USERDATA Dir

A path traversal flaw in the `clean_path()` helper let a user-controlled `rel_path` value escape the intended USERDATA directory and reach arbitrary files on disk. The function joined path segments without checking the final result, so `../` sequences in route parameters or query strings could be used to read or write files outside the sandboxed storage area. The fix normalizes the path and verifies it still resolves inside the USERDATA root before returning it, raising an error otherwise.

critical

path.resolve() Path Traversal in Node CLI's Dynamic import()

A Node.js CLI script for validating expression definitions took a file path from `process.argv[2]`, resolved it with `path.resolve()`, and passed the result straight into a dynamic `import()` — with no check that the resolved path stayed inside the working directory. An attacker (or a malicious skill/plugin invocation) could supply traversal sequences to load and execute arbitrary `.js` files from anywhere on disk. The fix adds a boundary check with `path.relative()` and an extension allowlist b

high

bookDir() Path Traversal via Unsanitized bookId Parameter

The `bookDir()` function accepted unsanitized `bookId` values derived from user-created book titles, enabling path traversal attacks through `../` sequences. A fix was applied that validates the identifier using `path.basename()` and throws on mismatch, ensuring all resolved paths remain within `LIBRARY_DIR`.

high

Express `app.get('*')` Wildcard Handler Path Traversal in watch.js

A first-party Express server's wildcard route handler used `req.url.indexOf('font.woff2')` to gate access to a font file, allowing attackers to bypass the substring check with crafted paths. The fix replaces the catch-all handler with explicit route registration.

high

updateCardBg() Follows Unvalidated 302 Location Headers

A background-image updater fetched a configured image URL with manual redirect handling and then re-issued the request to whatever `Location` header came back, with no scheme or host checks. A redirect to `http://169.254.169.254/` or `http://127.0.0.1:<port>/` would have been followed with the original fetch options attached, and the response body written to disk as an image asset. The fix resolves the redirect target against `imgDownloadUrl` and rejects anything that is not HTTPS on the same ho

high

markitdown_bridge.py Path Traversal: Arbitrary File Read via sys.argv

The markitdown_bridge.py script, used by MDView for DOCX-to-Markdown conversion, accepted file paths directly from command-line arguments without validating they stayed within intended directories. An attacker could exploit this to read arbitrary files from the filesystem by passing path traversal sequences in the source_path parameter.