Skip to content
Myr

fix(req): correct `c.req.param` decodes invalid percent strings (#3573)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(req): correct `c.req.param` decodes invalid percent strings * make `tryDecodeURIComponent` as a `const` function * use `/\%/.test()` for a better performance

authored by Yusuke Wada · committed by GitHub · parent e9de50d · Browse files · 3 files+24 added−44 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+24 added−44 removed

  • tests:+4 added−28 removed
  • other:+20 added−16 removed

3 files+24 added−44 removed

modified:src/utils/url.ts+15 added-12 removed
72 unmodified lines
7374 return null75}7677/**78 * Try to apply decodeURI() to given string.79 * If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible.80 * @param str The string to decode.81 * @returns The decoded string that sometimes contains undecodable percent encoding.82 * @example83 * tryDecodeURI('Hello%20World') // 'Hello World'84 * tryDecodeURI('Hello%20World/%A4%A2') // 'Hello World/%A4%A2'85 */86const tryDecodeURI = (str: string): string => {77type Decoder = (str: string) => string78export const tryDecode = (str: string, decoder: Decoder): string => {79 try {88 return decodeURI(str)80 return decoder(str)81 } catch {82 return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {83 try {92 return decodeURI(match)84 return decoder(match)85 } catch {86 return match87 }88 })89 }90}9192/**93 * Try to apply decodeURI() to given string.94 * If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible.95 * @param str The string to decode.96 * @returns The decoded string that sometimes contains undecodable percent encoding.97 * @example98 * tryDecodeURI('Hello%20World') // 'Hello World'99 * tryDecodeURI('Hello%20World/%A4%A2') // 'Hello World/%A4%A2'100 */101const tryDecodeURI = (str: string) => tryDecode(str, decodeURI)102103export const getPath = (request: Request): string => {104 const url = request.url105 const start = url.indexOf('/', 8)106 let i = start
207 unmodified lines
modified:src/hono.test.ts+4 added-28 removed
769 unmodified lines
770 })771772 it('should decode alphabets with invalid UTF-8 sequence', async () => {773 app.get('/static/:path', (c) => {774 try {775 return c.text(`by c.req.param: ${c.req.param('path')}`) // this should throw an error774 return c.text(`by c.req.param: ${c.req.param('path')}`)776 } catch (e) {777 return c.text(`by c.req.url: ${c.req.url.replace(/.*\//, '')}`)778 }775 })776777 const res = await app.request('http://localhost/%73tatic/%A4%A2') // %73 is 's', %A4%A2 is invalid UTF-8 sequence778 expect(res.status).toBe(200)783 expect(await res.text()).toBe('by c.req.url: %A4%A2')779 expect(await res.text()).toBe('by c.req.param: %A4%A2')780 })781782 it('should decode alphabets with invalid percent encoding', async () => {783 app.get('/static/:path', (c) => {788 try {789 return c.text(`by c.req.param: ${c.req.param('path')}`) // this should throw an error784 return c.text(`by c.req.param: ${c.req.param('path')}`)790 } catch (e) {791 return c.text(`by c.req.url: ${c.req.url.replace(/.*\//, '')}`)792 }785 })786787 const res = await app.request('http://localhost/%73tatic/%a') // %73 is 's', %a is invalid percent encoding788 expect(res.status).toBe(200)797 expect(await res.text()).toBe('by c.req.url: %a')789 expect(await res.text()).toBe('by c.req.param: %a')790 })791800 it('should be able to catch URIError', async () => {801 app.onError((err, c) => {802 if (err instanceof URIError) {803 return c.text(err.message, 400)804 }805 throw err806 })807 app.get('/static/:path', (c) => {808 return c.text(`by c.req.param: ${c.req.param('path')}`) // this should throw an error809 })810811 const res = await app.request('http://localhost/%73tatic/%a') // %73 is 's', %a is invalid percent encoding812 expect(res.status).toBe(400)813 expect(await res.text()).toBe('URI malformed')814 })815792 it('should not double decode', async () => {793 app.get('/users/:id', (c) => c.text(`posts of ${c.req.param('id')}`))794795 const res = await app.request('http://localhost/users/%2525') // %25 is '%'
2801 unmodified lines
modified:src/request.ts+5 added-4 removed
11 unmodified lines
12import { parseBody } from './utils/body'13import type { BodyData, ParseBodyOptions } from './utils/body'14import type { CustomHeader, RequestHeader } from './utils/headers'15import type { Simplify, UnionToIntersection } from './utils/types'16import { decodeURIComponent_, getQueryParam, getQueryParams } from './utils/url'16import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from './utils/url'1718type Body = {19 json: any20 text: string
2 unmodified lines
23 formData: FormData24}25type BodyCache = Partial<Body & { parsedBody: BodyData }>2627const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)2829export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {30 /**31 * `.raw` can get the raw Request object.32 *
63 unmodified lines
9697 private getDecodedParam(key: string): string | undefined {98 const paramKey = this.#matchResult[0][this.routeIndex][1][key]99 const param = this.getParamValue(paramKey)9899 return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined100 return param ? (/\%/.test(param) ? tryDecodeURIComponent(param) : param) : undefined101 }102103 private getAllDecodedParams(): Record<string, string> {104 const decoded: Record<string, string> = {}
1 unmodified line
106 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])107 for (const key of keys) {108 const value = this.getParamValue(this.#matchResult[0][this.routeIndex][1][key])109 if (value && typeof value === 'string') {109 decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value110 decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value111 }112 }113114 return decoded
292 unmodified lines