koajs / router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
MIT License
849 stars 174 forks source link

[fix] @koa/router does not handle decoding URL with '+' character properly #179

Closed stixsg closed 3 weeks ago

stixsg commented 5 months ago

Describe the bug

Node.js version: v20.12.0

OS version: Ubuntu 22.04

Description: @koa/router does not handle decoding URL with '+' character properly. With reference to https://en.wikipedia.org/wiki/Percent-encoding:

When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email.[3] The encoding used by default is based on an early version of the general URI percent-encoding rules,[4] with a number of modifications such as newline normalization and replacing spaces with + instead of %20. The media type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined in the HTML and XForms specifications. In addition, the CGI specification contains rules for how web servers decode data of this type and make it available to applications.

'+' characters in URL should be decoded as spaces.

Possible fix

According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#decoding_query_parameters_from_a_url, decodeURIComponent() cannot be used directly to parse query parameters from a URL. It needs a bit of preparation. In function safeDecodeURIComponent(text) in layer.js, call to decodeURIComponent() should first replace all '+' with spaces:


function safeDecodeURIComponent(text) {
  try {
    return decodeURIComponent(text.replace(/\+/g, " "));
  } catch {
    return text;
  }
}

Checklist

titanism commented 3 weeks ago

v13.0.0 released to npm 🎉

https://github.com/koajs/router/releases/tag/v13.0.0