Skip to content

Commit

Permalink
fix: encode switchLocalePath during SSR replacement (nuxt-modules#3043
Browse files Browse the repository at this point in the history
)
  • Loading branch information
BobbieGoede authored Jul 27, 2024
1 parent c4458f2 commit be59c76
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 2 deletions.
10 changes: 10 additions & 0 deletions specs/experimental/switch_locale_path_link_ssr.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,14 @@ describe('experimental.switchLocalePathLinkSSR', async () => {
expect(product2dom.querySelector('#i18n-alt-en').href).toEqual('/products/red-mug')
expect(product2dom.querySelector('#switch-locale-path-link-en').href).toEqual('/products/red-mug')
})

test('encode localized path to prevent XSS', async () => {
const url = `/experimental//"><script>console.log('xss')</script><`

const html = await $fetch(url)
const dom = getDom(html)

// the localized should be the same as encoded
expect(dom.querySelector('#slp-xss a').href).toEqual(encodeURI('/nl' + url))
})
})
8 changes: 8 additions & 0 deletions specs/fixtures/basic_usage/pages/experimental/[...slug].vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<script setup lang="ts"></script>

<template>
<h1>No XSS</h1>
<section id="slp-xss">
<SwitchLocalePathLink locale="nl">Switch to NL</SwitchLocalePathLink>
</section>
</template>
2 changes: 1 addition & 1 deletion src/runtime/components/SwitchLocalePathLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default defineComponent({

return () => [
h(Comment, `${SWITCH_LOCALE_PATH_LINK_IDENTIFIER}-[${props.locale}]`),
h(NuxtLink, { ...attrs, to: switchLocalePath(props.locale) }, slots.default),
h(NuxtLink, { ...attrs, to: encodeURI(switchLocalePath(props.locale)) }, slots.default),
h(Comment, `/${SWITCH_LOCALE_PATH_LINK_IDENTIFIER}`)
]
}
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/plugins/switch-locale-path-ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export default defineNuxtPlugin({

ctx.renderResult.html = ctx.renderResult.html.replaceAll(
switchLocalePathLinkWrapperExpr,
(match: string, p1: string) => match.replace(/href="([^"]+)"/, `href="${switchLocalePath(p1 ?? '')}"`)
(match: string, p1: string) =>
match.replace(/href="([^"]+)"/, `href="${encodeURI(switchLocalePath(p1 ?? ''))}"`)
)
})
}
Expand Down

0 comments on commit be59c76

Please sign in to comment.