Skip to content

Commit

Permalink
fix: Only sanitize the built string
Browse files Browse the repository at this point in the history
There is no need to sanitize the replacement values as it is sufficient to sanitize the result.
1. This will improve the performance if multiple placeholders are used.
2. This allows this: `See {linkstart}documentation{linkend}` with `{ linkstart: '<a ...>', linkend: '</a>' }` while the string is still sanitized.

Signed-off-by: Ferdinand Thiessen <opensource@fthiessen.de>
  • Loading branch information
susnux committed Jun 27, 2023
1 parent 749fefc commit f112d14
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 f112d14

Please sign in to comment.