Skip to content

Commit fa66f1a

Browse files
authored
FIX: Ensure translated content is safe for rendering (#220)
As much as we would like to trust AI / translation API outputs, we're adding a bit of sanitisation here for simple things like script tags in case.
1 parent e76b467 commit fa66f1a

File tree

4 files changed

+28
-0
lines changed

4 files changed

+28
-0
lines changed

.discourse-compatibility

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
< 3.5.0.beta2-dev: 5f24835801fdc7cb98e1bcf42d2ab2e49e609921
12
< 3.5.0.beta1-dev: 7d411e458bdd449f8aead2bc07cedeb00b856798
23
< 3.4.0.beta3-dev: b4cf3a065884816fa3f770248c2bf908ba65d8ac
34
< 3.4.0.beta1-dev: 5346b4bafba2c2fb817f030a473b7bbca97b909c

app/models/concerns/discourse_translator/translatable.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,14 @@ def set_detected_locale(locale)
1717
(content_locale || build_content_locale).update!(detected_locale: locale)
1818
end
1919

20+
# This method is used to create a translation for a translatable (Post or Topic) and a specific locale.
21+
# If a translation already exists for the locale, it will be updated.
22+
# Texts are put through a Sanitizer to clean them up before saving.
23+
# @param locale [String] the locale of the translation
24+
# @param text [String] the translated text
2025
def set_translation(locale, text)
2126
locale = locale.to_s.gsub("_", "-")
27+
text = DiscourseTranslator::TranslatedContentSanitizer.sanitize(text)
2228
translations.find_or_initialize_by(locale: locale).update!(translation: text)
2329
end
2430

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# frozen_string_literal: true
2+
3+
module DiscourseTranslator
4+
class TranslatedContentSanitizer
5+
def self.sanitize(content)
6+
PrettyText.cleanup(content, {})
7+
end
8+
end
9+
end
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# frozen_string_literal: true
2+
3+
describe DiscourseTranslator::TranslatedContentSanitizer do
4+
it "sanitizes the content" do
5+
sanitized =
6+
DiscourseTranslator::TranslatedContentSanitizer.sanitize(
7+
"<script>alert('test')</script><p> <h1>Testing</h1> This is a test post</p>",
8+
)
9+
10+
expect(sanitized).to eq("<p> </p><h1>Testing</h1> This is a test post<p></p>")
11+
end
12+
end

0 commit comments

Comments
 (0)