Skip to content

fix: handle invalid Referrer URLs in back() without crashing#1948

Open
guoyangzhen wants to merge 3 commits intokoajs:masterfrom
guoyangzhen:fix/back-invalid-referrer
Open

fix: handle invalid Referrer URLs in back() without crashing#1948
guoyangzhen wants to merge 3 commits intokoajs:masterfrom
guoyangzhen:fix/back-invalid-referrer

Conversation

@guoyangzhen
Copy link
Copy Markdown

@guoyangzhen guoyangzhen commented Apr 1, 2026

Description

Both redirect() and back() called new URL() without error handling. Invalid URL input (malformed, malicious, or incomplete) would throw an uncaught TypeError and crash the request with a 500 error.

redirect()

// Before
url = new URL(url).toString() // throws on 'https://' or '://invalid'

// After
try {
  url = new URL(url).toString()
} catch {
  // invalid URL, encode as-is
}

back()

// Before
const url = new URL(referrer, this.ctx.href) // throws on invalid Referrer

// After
try {
  const url = new URL(referrer, this.ctx.href)
  if (url.host === this.ctx.host) { ... }
} catch {
  // invalid URL, fall through to alt
}

Impact

Without this fix, a request with Referrer: ://invalid or Location: https:// crashes the entire request handler.

Fixes koajs#1746

The origin getter returned this.req.headers.origin (the CORS Origin header)
which ignores the proxy flag. Changed to construct origin from protocol and
host getters, which already respect X-Forwarded-Proto and X-Forwarded-Host
when app.proxy is true.
…id URLs

The back() method called new URL(referrer) without error handling.
An invalid Referrer header (e.g. '://invalid', malicious input)
would throw an uncaught TypeError and crash the request.

Now catches the error and falls through to the alt parameter.
Both redirect() and back() called new URL() without error handling.
Invalid URL input (malformed, malicious, or incomplete) would throw
an uncaught TypeError and crash the request.

Changes:
- redirect(): wrap new URL(url) in try-catch, fall back to encoding as-is
- back(): wrap new URL(referrer) in try-catch, fall back to alt parameter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant