Skip to content

Commit b982c02

Browse files
usualomayusukebe
andauthored
Merge commit from fork
* fix(url): stabilize paths with malformed percent escapes Preserve percent escapes during fallback decoding and prevent malformed escapes from changing meaning after URL serialization, while keeping stable paths such as /100% unchanged. Check path stability against a fixed HTTP base so an unparsable request authority cannot make getPath throw before error handling. * fix(mount): safely forward routed paths to mounted apps Slice the matched mount prefix from the parent routed path, including after route grouping, and preserve backslashes and control characters when rebuilding the request URL. Reject dot segments and malformed percent encoding or UTF-8 that changes after URL serialization and decoding. Reject ambiguous request URL authorities, and count trailing slashes in the received URL before parsing so non-strict parent and child applications cannot remove different slashes. Preserve stable malformed paths, valid custom getPath encodings, replaceRequest overrides, and existing configuration errors. Cover both mount APIs with regression tests. * fix(mount): reject optional regular expression parameters Reject unsupported optional regular expression parameters as configuration errors before measuring the mount prefix. Previously they were measured as literal route text, allowing certain path lengths to forward an unintended suffix past parent authorization. Throw Error so the default error handler responds with HTTP 500, consistently with other unsupported mount configurations. Keep HTTP 400 for request paths that cannot be forwarded safely, and update both mount APIs' throws documentation. Cover short and matching-length inputs, slash-matching patterns, optional parameters in the middle of a route, custom error handling, and both mount APIs with PatternRouter. Verify separate route registrations as the supported workaround. * remove unused stripPathPrefix --------- Co-authored-by: Yusuke Wada <[email protected]>
1 parent 9aeb45b commit b982c02

8 files changed

Lines changed: 592 additions & 71 deletions

File tree

‎src/hono-base.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import { compose } from './compose'
88
import { Context } from './context'
99
import type { ExecutionContext } from './context'
10+
import { routePath } from './helper/route'
1011
import type { Router } from './router'
1112
import { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'
1213
import type {
@@ -323,6 +324,8 @@ class Hono<
323324
* @param {Function} applicationHandler - other Request Handler
324325
* @param {MountOptions} [options] - options of `.mount()`
325326
* @returns {Hono} mounted Hono instance
327+
* @throws {Error} If automatic request rewriting encounters duplicate path parameter names or an optional regular expression parameter.
328+
* @throws {HTTPException} With status 400 if automatic request rewriting cannot safely preserve the routed path.
326329
*
327330
* @example
328331
* ```ts
@@ -380,9 +383,10 @@ class Hono<
380383
} catch {} // Do nothing
381384
return [c.env, executionContext]
382385
}
383-
const mergedPath = mergePath(this._basePath, path)
384-
const defaultReplaceRequest = (c: Context): Request =>
385-
createMountedRequest(c, mergedPath.replace(/\/$/, ''), mergePath(mergedPath, '*'))
386+
const defaultReplaceRequest = (c: Context): Request => {
387+
const mountedRoutePath = routePath(c)
388+
return createMountedRequest(c, mountedRoutePath.replace(/\/?\*$/, ''), mountedRoutePath)
389+
}
386390

387391
const handler: MiddlewareHandler = async (c, next) => {
388392
const request = replaceRequest ? replaceRequest(c.req.raw) : defaultReplaceRequest(c)

‎src/hono.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2633,6 +2633,20 @@ describe('Optional parameters', () => {
26332633

26342634
describe('app.mount()', () => {
26352635
describe('Basic', () => {
2636+
it.each([
2637+
['/api', '/api/x/foo'],
2638+
['/:tenant', '/acme/x/foo'],
2639+
])('Should strip the route() prefix %s', async (base, input) => {
2640+
const child = new Hono()
2641+
child.mount('/x', (req) => new Response(getPath(req)))
2642+
const app = new Hono()
2643+
app.route(base, child)
2644+
2645+
const res = await app.request(input)
2646+
expect(res.status).toBe(200)
2647+
expect(await res.text()).toBe('/foo')
2648+
})
2649+
26362650
const anotherApp = (req: Request, ...params: unknown[]) => {
26372651
const path = getPath(req)
26382652
if (path === '/') {

‎src/middleware/mount/index.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,51 @@ describe('mount()', () => {
210210
})
211211
})
212212

213+
describe('With an optional regular expression parameter', () => {
214+
it.each([
215+
['/mount/:id{[0-9]+}?', '/mount'],
216+
['/mount/:id{[0-9]+}?', '/mount/123'],
217+
['/mount/:id{[0-9]+}?', '/mount/123456789012'],
218+
['/mount/:path{.+}?', '/mount/aaaaaaaaaa/admin/secret'],
219+
['/mount/:v{v[0-9]+}?/:id?', '/mount/v1234567890123456/admin'],
220+
])(
221+
'Should return 500 for unsupported automatic request rewriting of %s at %s',
222+
async (route, path) => {
223+
const anotherApp = vi.fn(() => new Response('Unexpected forwarding'))
224+
const onError = vi.fn((err: Error) => new Response(err.message, { status: 500 }))
225+
const app = new Hono()
226+
app.onError(onError)
227+
app.all(route, mount(anotherApp))
228+
229+
const res = await app.request(path)
230+
231+
expect(res.status).toBe(500)
232+
expect(await res.text()).toBe(
233+
`mount(): Optional regular expression parameters are not supported in "${route}".`
234+
)
235+
expect(onError).toHaveBeenCalledOnce()
236+
expect(onError.mock.calls[0][0].constructor).toBe(Error)
237+
expect(anotherApp).not.toHaveBeenCalled()
238+
}
239+
)
240+
241+
it.each(['/mount', '/mount/123'])(
242+
'Should support separate route registrations for %s',
243+
async (path) => {
244+
const anotherApp = vi.fn((req: Request) => new Response(getPath(req)))
245+
const app = new Hono()
246+
app.all('/mount', mount(anotherApp))
247+
app.all('/mount/:id{[0-9]+}', mount(anotherApp))
248+
249+
const res = await app.request(path)
250+
251+
expect(res.status).toBe(200)
252+
expect(await res.text()).toBe('/')
253+
expect(anotherApp).toHaveBeenCalledOnce()
254+
}
255+
)
256+
})
257+
213258
describe('With a wildcard inside the last segment', () => {
214259
it.each([
215260
['/assets*', '/assets/hello'],

‎src/middleware/mount/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ const defaultGetOptions = (c: Context): unknown[] => {
4141
* @param {Function} applicationHandler - other Request Handler
4242
* @param {MountOptions} [options] - options of `mount()`
4343
* @returns {MiddlewareHandler} handler to register with `app.all()`
44-
* @throws {Error} If the route ends with a wildcard inside a segment (e.g. `/assets*`), or automatic request rewriting encounters duplicate path parameter names.
44+
* @throws {Error} If the route ends with a wildcard inside a segment (e.g. `/assets*`), or automatic request rewriting encounters duplicate path parameter names or an optional regular expression parameter.
45+
* @throws {HTTPException} With status 400 if automatic request rewriting cannot safely preserve the routed path.
4546
*
4647
* @example
4748
* ```ts

0 commit comments

Comments
 (0)