ttag-org / ttag

:orange_book: simple approach for javascript localization
https://ttag.js.org/
MIT License
338 stars 41 forks source link

`ngettext` causes unsafe-eval CSP error #185

Closed mmso closed 4 years ago

mmso commented 4 years ago

Hello, on our application we don't allow eval in our CSP policy, so ngettext causes the following error:

Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval'

at new Function (<anonymous>)
    at createPluralFunc (ttag.js:84)
    at getPluralFunc (ttag.js:84)
    at Config.getDefaultPluralFn (ttag.js:521)
    at Context.ngettext (ttag.js:727)

it's possibly from https://github.com/ttag-org/ttag/blob/master/src/utils.js#L52 or https://github.com/ttag-org/plural-forms/blob/master/src/lib.js#L20

Do you have any idea how to get around this issue without changing our CSP policy?

AlexMost commented 4 years ago

Hi @mmso! I guess it happens when we are trying to create plural func that is retrieved from the .po file data. To be able to avoid this we should insert all plural functions for all languages inside the sources. This will increase the library, need to check how much size it will add.

mmso commented 4 years ago

Thanks for your quick reply @AlexMost. Yes the extra size cost would be an ok tradeoff for us in this case.

Perhaps ideally it could be configurable?

AlexMost commented 4 years ago

You can try the new safe version 1.7.19. It doesn't use eval. It adds only +1KB to the lib size. Let me know if that works for you.

mmso commented 4 years ago

Thank you @AlexMost, that works like a charm!

mmso commented 4 years ago

Scratch that. It still doesn't work because https://github.com/ttag-org/ttag/blob/master/src/utils.js#L184 language ended up being 0 here, I made one PR here https://github.com/ttag-org/ttag/pull/187.

And the other issue is that we are using the compact compilation, which removes language from the header https://github.com/ttag-org/ttag-cli/blob/master/src/commands/po2json.ts#L23.

AlexMost commented 4 years ago

Thanks for the research) I have merged your PR + added language to compact format. You can try:

mmso commented 4 years ago

Thanks again :)