Skip to content

Commit

Permalink
Merge pull request #648 from nextcloud-libraries/fix/only-sanitize-fu…
Browse files Browse the repository at this point in the history
…ll-string

fix!: Only sanitize the result string when replacing variables
  • Loading branch information
susnux authored Sep 24, 2023
2 parents 7a542ea + 586c3b2 commit d97aee1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
14 changes: 9 additions & 5 deletions lib/translation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,18 @@ export function translate(
const _build = (text: string, vars?: Record<string, string | number>, number?: number) => {
return text.replace(/%n/g, '' + number).replace(/{([^{}]*)}/g, (match, key) => {
if (vars === undefined || !(key in vars)) {
return optSanitize(match)
return optEscape(match)
}

const r = vars[key]
if (typeof r === 'string' || typeof r === 'number') {
return optSanitize(optEscape(r))
const replacement = vars[key]
if (typeof replacement === 'string' || typeof replacement === 'number') {
return optEscape(`${replacement}`)
} else {
return optSanitize(match)
/* This should not happen,
* but the variables are used defined so not allowed types could still be given,
* in this case ignore the replacement and use the placeholder
*/
return optEscape(match)
}
})
}
Expand Down
6 changes: 6 additions & 0 deletions tests/translation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ describe('translate', () => {
expect(translation).toBe('Hallo <del>Name</del>')
})

it('without placeholder HTML escaping on links', () => {
const text = 'Hello {start}Nextcloud{end}'
const translation = translate('core', text, { start: '<a href="https://nextcloud.com">', end: '</a>' }, undefined, { escape: false })
expect(translation).toBe('Hello <a href="https://nextcloud.com">Nextcloud</a>')
})

it('with placeholder HTML escaping', () => {
const text = 'Hello {name}'
const translation = translate('core', text, { name: '<del>Name</del>' })
Expand Down

0 comments on commit d97aee1

Please sign in to comment.