Skip to content

Commit 9123ed8

Browse files
committed
fix(nuxt): match route rules against decoded paths
1 parent 8fb72c0 commit 9123ed8

11 files changed

Lines changed: 178 additions & 20 deletions

File tree

‎packages/nitro-server/src/index.ts‎

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ import { LOOPBACK_HOSTS, isLocalDevRequest, isLoopbackPeer } from './dev-request
3030
import { template as defaultSpaLoadingTemplate } from './templates/spa-loading-icon.ts'
3131
// TODO: figure out a good way to share this
3232
import { createImportProtectionPatterns } from '../../nuxt/src/core/plugins/import-protection.ts'
33+
import { normalizeRouteRulePath } from '../../nuxt/src/core/utils/route-rules.ts'
34+
import { decodeRoutePath } from '../../nuxt/src/core/utils/index.ts'
3335
import { nitroSchemaTemplate } from './templates.ts'
3436
// Re-export a type from the augment module rather than a bare `import './augments.ts'`
3537
// side-effect import to work around bug in oxc's dts emitter which drops side-effect-only imports
@@ -396,26 +398,29 @@ export async function bundle (nuxt: Nuxt & { _nitro?: Nitro }): Promise<void> {
396398
// rou3 matches keys case-sensitively, but vue-router matches routes case-insensitively
397399
// unless `sensitive`, so an insensitive-routing rule keyed `/Admin` would never match a
398400
// folded lookup and silently lose its protections. `sensitive` can also come from
399-
// `app/router.options.ts` (runtime-only), so emit both a verbatim and a folded matcher
400-
// and pick at runtime.
401+
// `app/router.options.ts` (runtime-only), so emit both a decoded and a decoded+folded
402+
// matcher and pick at runtime.
401403
const caseSensitiveRouteRules = !!nuxt.options.router.options.sensitive
402-
const foldRouteRuleKey = (route: string) => caseSensitiveRouteRules || typeof route !== 'string' ? route : route.toLowerCase()
404+
405+
// Both matchers are compiled on every build, so collisions are reported once rather
406+
// than once per compilation pass.
407+
const warnedKeyCollisions = new Set<string>()
403408

404409
function getRouteRulesRouter (fold: boolean) {
405410
const routeRulesRouter = createRou3Router<NitroRouteRules>()
406411
if (nuxt._nitro) {
407-
const foldedKeys = new Map<string, string>()
412+
const normalizedKeys = new Map<string, string>()
408413
for (const [route, rules] of Object.entries(nuxt._nitro.options.routeRules)) {
409414
if (route === '/__nuxt_error') { continue }
410415
if (validManifestKeys.every(key => !(key in rules))) { continue }
411-
const key = fold && typeof route === 'string' ? route.toLowerCase() : route
412-
if (fold) {
413-
const existing = foldedKeys.get(key)
414-
if (existing !== undefined && existing !== route && !caseSensitiveRouteRules) {
415-
logger.warn(`Route rules for \`${existing}\` and \`${route}\` resolve to the same path when matched case-insensitively; \`${route}\` takes precedence. Disambiguate the keys or set \`router.options.sensitive: true\`.`)
416-
}
417-
foldedKeys.set(key, route)
416+
const key = normalizeRouteRulePath(route, fold)
417+
const existing = normalizedKeys.get(key)
418+
// Only the matcher that will actually be used at runtime should report collisions.
419+
if (existing !== undefined && existing !== route && fold !== caseSensitiveRouteRules && !warnedKeyCollisions.has(key)) {
420+
warnedKeyCollisions.add(key)
421+
logger.warn(`Route rules for \`${existing}\` and \`${route}\` resolve to the same path; \`${route}\` takes precedence. Disambiguate the keys${fold ? ' or set `router.options.sensitive: true`' : ''}.`)
418422
}
423+
normalizedKeys.set(key, route)
419424
addRoute(routeRulesRouter, undefined, key, rules)
420425
}
421426
}
@@ -468,9 +473,19 @@ export async function bundle (nuxt: Nuxt & { _nitro?: Nitro }): Promise<void> {
468473
`import routerOptions from '#build/router.options.mjs'`,
469474
`const sensitiveMatcher = ${sensitiveMatcher}`,
470475
foldedMatcher === sensitiveMatcher ? `const foldedMatcher = sensitiveMatcher` : `const foldedMatcher = ${foldedMatcher}`,
476+
// `decodeRoutePath` has no free variables, so it can be inlined by source to keep
477+
// the runtime lookup and the build-time key normalisation from drifting apart.
478+
`const decodeRoutePath = ${decodeRoutePath.toString()}`,
479+
// Decoding must precede case folding, or a percent-encoded non-ASCII character
480+
// would never fold.
481+
`const normalizePath = (path, fold) => {`,
482+
` if (typeof path !== 'string') { return path }`,
483+
` const decoded = decodeRoutePath(path)`,
484+
` return fold ? decoded.toLowerCase() : decoded`,
485+
`}`,
471486
`export default (path) => routerOptions.sensitive`,
472-
` ? defu({}, ...sensitiveMatcher('', path).map(r => r.data).reverse())`,
473-
` : defu({}, ...foldedMatcher('', typeof path === 'string' ? path.toLowerCase() : path).map(r => r.data).reverse())`,
487+
` ? defu({}, ...sensitiveMatcher('', normalizePath(path, false)).map(r => r.data).reverse())`,
488+
` : defu({}, ...foldedMatcher('', normalizePath(path, true)).map(r => r.data).reverse())`,
474489
].join('\n')
475490
},
476491
})
@@ -560,7 +575,7 @@ export async function bundle (nuxt: Nuxt & { _nitro?: Nitro }): Promise<void> {
560575
for (const route of nitro._prerenderedRoutes) {
561576
if (!route.error && route.route.endsWith(payloadSuffix)) {
562577
const url = route.route.slice(0, -payloadSuffix.length) || '/'
563-
const rules = defu({}, ...findAllRoutes(routeRulesMatcher, undefined, foldRouteRuleKey(url)).reverse()) as Record<string, any>
578+
const rules = defu({}, ...findAllRoutes(routeRulesMatcher, undefined, normalizeRouteRulePath(url, !caseSensitiveRouteRules)).reverse()) as Record<string, any>
564579
if (!rules.prerender) {
565580
prerenderedRoutes.add(url)
566581
}

‎packages/nuxt/src/core/utils/index.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,21 @@ export function uniqueBy<T, K extends keyof T> (arr: T[], key: K) {
1818
export const QUOTE_RE = /["']/g
1919
export const EXTENSION_RE = /\b\.\w+$/g
2020
export const SX_RE = /\.[tj]sx$/
21+
22+
/**
23+
* Decode a route path for route-rule matching, returning it unchanged if it is not
24+
* percent-encoded or cannot be decoded. Reserved characters (`%2F`, `%3F`, …) are
25+
* left encoded, so decoding cannot introduce additional path segments. Only the path
26+
* portion is decoded; a query string, if present, is left untouched to avoid
27+
* double-decoding it.
28+
*/
29+
export function decodeRoutePath (path: string) {
30+
if (!path.includes('%')) { return path }
31+
const queryIndex = path.indexOf('?')
32+
const pathname = queryIndex === -1 ? path : path.slice(0, queryIndex)
33+
try {
34+
return queryIndex === -1 ? decodeURI(pathname) : decodeURI(pathname) + path.slice(queryIndex)
35+
} catch {
36+
return path
37+
}
38+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { decodeRoutePath } from './index.ts'
2+
3+
/**
4+
* Normalise a route-rule key or lookup path: decode percent-encoding, then case-fold when
5+
* `fold` is set. Keys are matched in decoded form so that a rule may be authored either
6+
* decoded (`/测试`, the usual case) or encoded (`/%E6%B5%8B%E8%AF%95`, the form the page route
7+
* and the request path take). Decoding must precede case folding, or a percent-encoded
8+
* non-ASCII character would never fold.
9+
*
10+
* @internal
11+
*/
12+
export function normalizeRouteRulePath (path: string, fold: boolean): string {
13+
const decoded = decodeRoutePath(path)
14+
return fold ? decoded.toLowerCase() : decoded
15+
}

‎packages/nuxt/src/pages/module.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type { PagesContext } from './utils.ts'
1919
import { globRouteRulesFromPages, removePagesRules } from './route-rules.ts'
2020
import { PageMetaPlugin } from './plugins/page-meta.ts'
2121
import { toVirtualId } from '../core/plugins/virtual.ts'
22+
import { normalizeRouteRulePath } from '../core/utils/route-rules.ts'
2223
import { RouteInjectionPlugin } from './plugins/route-injection.ts'
2324
import type { Nuxt, NuxtPage } from 'nuxt/schema'
2425
import type { InlinePreset } from 'unimport'
@@ -537,17 +538,16 @@ export default defineNuxtModule({
537538

538539
// Inject page patterns that explicitly match `prerender: true` route rule
539540
if (!nitro.options.static) {
540-
// Match route rules case-insensitively (unless routing is `sensitive`) to
541-
// mirror the compiled `#build/route-rules.mjs` matcher, so a `prerender: true`
542-
// rule keyed `/Admin` is honoured for the page derived at `/Admin`.
541+
// Normalise keys and lookups the same way as the compiled `#build/route-rules.mjs`
542+
// matcher: decode percent-encoding (page routes are encoded, rule keys usually are
543+
// not), then case-fold unless routing is `sensitive`.
543544
const caseSensitiveRouteRules = !!nuxt.options.router.options.sensitive
544-
const foldRouteRuleKey = (route: string) => caseSensitiveRouteRules ? route : route.toLowerCase()
545545
const routeRulesRouter = createRou3Router<NitroRouteRules>()
546546
for (const [route, rules] of Object.entries(nitro.options.routeRules)) {
547-
addRoute(routeRulesRouter, undefined, foldRouteRuleKey(route), rules)
547+
addRoute(routeRulesRouter, undefined, normalizeRouteRulePath(route, !caseSensitiveRouteRules), rules)
548548
}
549549
for (const route of prerenderRoutes) {
550-
const rules = defu({} as Record<string, any>, ...findAllRoutes(routeRulesRouter, undefined, foldRouteRuleKey(route)).reverse())
550+
const rules = defu({} as Record<string, any>, ...findAllRoutes(routeRulesRouter, undefined, normalizeRouteRulePath(route, !caseSensitiveRouteRules)).reverse())
551551
if (rules.prerender) {
552552
nitro.options.prerender.routes.push(route)
553553
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { describe, expect, it } from 'vitest'
2+
3+
import { decodeRoutePath } from '../src/core/utils/index.ts'
4+
5+
describe('decodeRoutePath', () => {
6+
it('decodes percent-encoded paths', () => {
7+
expect(decodeRoutePath('/pre/t%65st')).toBe('/pre/test')
8+
expect(decodeRoutePath('/%E6%B5%8B%E8%AF%95')).toBe('/测试')
9+
})
10+
11+
it('decodes double-encoded sequences only once', () => {
12+
expect(decodeRoutePath('/pre/%2574est')).toBe('/pre/%74est')
13+
})
14+
15+
it('leaves reserved characters encoded', () => {
16+
expect(decodeRoutePath('/pre%2Ftest')).toBe('/pre%2Ftest')
17+
expect(decodeRoutePath('/pre%3Ftest')).toBe('/pre%3Ftest')
18+
})
19+
20+
it('returns unchanged paths that are not percent-encoded or cannot be decoded', () => {
21+
expect(decodeRoutePath('/pre/test')).toBe('/pre/test')
22+
expect(decodeRoutePath('/100% legit')).toBe('/100% legit')
23+
expect(decodeRoutePath('/caf%C3')).toBe('/caf%C3')
24+
})
25+
26+
it('decodes only the path portion of a query-bearing path', () => {
27+
expect(decodeRoutePath('/pre/t%65st?next=%252Fhome')).toBe('/pre/test?next=%252Fhome')
28+
expect(decodeRoutePath('/pre/test?next=%41')).toBe('/pre/test?next=%41')
29+
})
30+
})

‎test/basic.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ describe('route rules', () => {
107107
expect(html).toContain('Hello from routeRules!')
108108
})
109109

110+
it('should run appMiddleware from a decoded route rule key on a unicode page', async () => {
111+
const html = await $fetch<string>(`/route-rules/${encodeURIComponent('测试')}`)
112+
expect(html).toContain('Hello from routeRules!')
113+
})
114+
110115
it('should run appMiddleware from an uppercase-keyed route rule regardless of request casing', async () => {
111116
for (const path of ['/route-rules/case-insensitive', '/Route-Rules/Case-Insensitive', '/ROUTE-RULES/CASE-INSENSITIVE']) {
112117
const html = await $fetch<string>(path)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<template>
2+
<div>
3+
<div>Greeting: {{ $route.meta.hello }}</div>
4+
</div>
5+
</template>

‎test/fixtures/basic/nuxt.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,8 @@ export default withMatrix({
184184
'/route-rules/middleware': { appMiddleware: 'route-rules-middleware' },
185185
// Uppercase-keyed rule must still apply to the case-insensitively served page.
186186
'/Route-Rules/Case-Insensitive': { appMiddleware: 'route-rules-middleware' },
187+
// Decoded key must still apply to the percent-encoded path generated for the page.
188+
'/route-rules/测试': { appMiddleware: 'route-rules-middleware' },
187189
'/route-rules/layout': { appLayout: 'custom' },
188190
'/spa-plugin-redirect/**': { ssr: false },
189191
'/no-scripts': { noScripts: true },

‎test/nuxt/composables.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,12 +583,24 @@ describe.skipIf(!isTestingAppManifest)('app manifests', () => {
583583
"/Legacy/Home": {
584584
"redirect": "/target",
585585
},
586+
"/cafÉ": {
587+
"redirect": "/accented-target",
588+
},
589+
"/pre-encoded/%E6%B5%8B%E8%AF%95": {
590+
"redirect": "/pre-encoded-target",
591+
},
586592
"/pre/test": {
587593
"redirect": "/",
588594
},
589595
"/specific-prerendered": {
590596
"prerender": true,
591597
},
598+
"/unicode/测试": {
599+
"ssr": false,
600+
},
601+
"/测试": {
602+
"redirect": "/unicode-target",
603+
},
592604
},
593605
"wildcard": {
594606
"/Secret/Docs": {
@@ -604,6 +616,9 @@ describe.skipIf(!isTestingAppManifest)('app manifests', () => {
604616
"prerender": true,
605617
"ssr": false,
606618
},
619+
"/unicode": {
620+
"ssr": true,
621+
},
607622
},
608623
},
609624
"prerendered": [],
@@ -653,6 +668,38 @@ describe('case-insensitive route rules', () => {
653668
expect(getRouteRules({ path }), path).toMatchObject({ redirect: '/target' })
654669
}
655670
})
671+
672+
it('folds a non-ASCII character that arrives percent-encoded', () => {
673+
for (const path of ['/cafÉ', '/café', `/caf${encodeURIComponent('É')}`, `/caf${encodeURIComponent('é')}`]) {
674+
expect(getRouteRules({ path }), path).toMatchObject({ redirect: '/accented-target' })
675+
}
676+
})
677+
})
678+
679+
describe('unicode route rules', () => {
680+
it('applies a decoded rule key to the encoded request path', () => {
681+
for (const path of ['/测试', `/${encodeURIComponent('测试')}`, `/${encodeURIComponent('测试').toLowerCase()}`]) {
682+
expect(getRouteRules({ path }), path).toMatchObject({ redirect: '/unicode-target' })
683+
}
684+
})
685+
686+
it('prefers a specific unicode rule over a catch-all covering the same key', () => {
687+
for (const path of ['/unicode/测试', `/unicode/${encodeURIComponent('测试')}`]) {
688+
expect(getRouteRules({ path }), path).toMatchObject({ ssr: false })
689+
}
690+
})
691+
692+
it('applies a rule key authored in encoded form', () => {
693+
for (const path of [`/pre-encoded/${encodeURIComponent('测试')}`, '/pre-encoded/测试']) {
694+
expect(getRouteRules({ path }), path).toMatchObject({ redirect: '/pre-encoded-target' })
695+
}
696+
})
697+
698+
it('applies a rule key whose casing matches the request exactly', () => {
699+
for (const path of ['/cafÉ', `/caf${encodeURIComponent('É')}`]) {
700+
expect(getRouteRules({ path }), path).toMatchObject({ redirect: '/accented-target' })
701+
}
702+
})
656703
})
657704

658705
describe('compiled route rules', () => {

‎test/nuxt/sensitive/route-rules.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,17 @@ describe('sensitive routing preserves route-rule casing', () => {
1313
it('does not fold a lowercase request onto an uppercase key', () => {
1414
expect(getRouteRules({ path: '/ADMIN/DASHBOARD' })).not.toHaveProperty('redirect')
1515
})
16+
17+
it('still decodes percent-encoded paths', () => {
18+
for (const path of ['/测试', `/${encodeURIComponent('测试')}`]) {
19+
expect(getRouteRules({ path }), path).toMatchObject({ redirect: '/unicode-target' })
20+
}
21+
})
22+
23+
it('does not fold a decoded non-ASCII character onto a differently cased key', () => {
24+
for (const path of ['/café', `/caf${encodeURIComponent('é')}`]) {
25+
expect(getRouteRules({ path }), path).not.toHaveProperty('redirect')
26+
}
27+
expect(getRouteRules({ path: `/caf${encodeURIComponent('É')}` })).toMatchObject({ redirect: '/accented-target' })
28+
})
1629
})

0 commit comments

Comments
 (0)