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
Provenance
- Commit
2bde76d- Tree
a5c0958- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
e9de50d
3 files changed+24 added−44 removed
modified:src/utils/url.ts+15 added-12 removed
72 unmodified lines73 74 return null75 }76 77-/**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- */86-const tryDecodeURI = (str: string): string => {77+type Decoder = (str: string) => string78+export 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 }91 92+/**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+ */101+const tryDecodeURI = (str: string) => tryDecode(str, decodeURI)102+103 export const getPath = (request: Request): string => {104 const url = request.url105 const start = url.indexOf('/', 8)106 let i = start207 unmodified linesmodified:src/hono.test.ts+4 added-28 removed
769 unmodified lines770 })771 772 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 })776 777 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 })781 782 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 })786 787 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 })791 800- 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- })810-811- 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- })815-792 it('should not double decode', async () => {793 app.get('/users/:id', (c) => c.text(`posts of ${c.req.param('id')}`))794 795 const res = await app.request('http://localhost/users/%2525') // %25 is '%'2801 unmodified linesmodified:src/request.ts+5 added-4 removed
11 unmodified lines12 import { parseBody } from './utils/body'13 import type { BodyData, ParseBodyOptions } from './utils/body'14 import type { CustomHeader, RequestHeader } from './utils/headers'15 import type { Simplify, UnionToIntersection } from './utils/types'16-import { decodeURIComponent_, getQueryParam, getQueryParams } from './utils/url'16+import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from './utils/url'17 18 type Body = {19 json: any20 text: string2 unmodified lines23 formData: FormData24 }25 type BodyCache = Partial<Body & { parsedBody: BodyData }>26 27+const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)28+29 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {30 /**31 * `.raw` can get the raw Request object.32 *63 unmodified lines96 97 private getDecodedParam(key: string): string | undefined {98 const paramKey = this.#matchResult[0][this.routeIndex][1][key]99 const param = this.getParamValue(paramKey)98-99- return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined100+ return param ? (/\%/.test(param) ? tryDecodeURIComponent(param) : param) : undefined101 }102 103 private getAllDecodedParams(): Record<string, string> {104 const decoded: Record<string, string> = {}1 unmodified line106 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 }113 114 return decoded292 unmodified lines