Не удалось загрузить вложение js

I am getting exactly the same error as this question i.e I can upload js files after allowing it in the settings but when I try to download it, the url in the browser changes to the js file url and " The change you wanted was rejected." is displayed.

Environment:-
Discourse docker running behind Nginx (nginx is using SSL)

Discourse container logs:-

    Started GET "p5ePkm5OoKveknnMjyArlS4PPwS.js" for 192.168.32.1 at 2021-02-22 05:48:52 +0000
    Processing by UploadsController#show_short as JS
      Parameters: {"base62"=>"p5ePkm5OoKveknnMjyArlS4PPwS", "extension"=>"js"}
    Sent file afcdf626f9db8d54a1fb5e8ebcab0ea214d9226a.js (2.2ms)
    Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.
    Completed 422 Unprocessable Entity in 59ms (ActiveRecord: 0.0ms | Allocations: 17414)
    ActionController::InvalidCrossOriginRequest (Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.)
    /opt/bitnami/discourse/vendor/bundle/ruby/2.6.0/gems/actionpack-6.0.3.1/lib/action_controller/metal/request_forgery_protection.rb:266:in `verify_same_origin_request'

Nginx logs:-

    10.164.0.103 - - [22/Feb/2021:05:51:11 +0000] "GET /uploads/short-url/p5ePkm5OoKveknnMjyArlS4PPwS.js HTTP/2.0" 422 781 "getting-started-with-sftp-module/292" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
``

Any help or pointers is appreciated!
2 лайка

Are you allowing *.js files to be attached to posts by users? Do you have legitimate need for javascript file attachments by your users? Just want to absolutely confirm before we proceed any further.

1 лайк

Thank you for quick response!
Yes, it is a coding Q/A discussion, so attaching *.js code files is a legitimate use case.

2 лайка

Hi All! I’m having the same issue. We’ve allowed .js extension to be uploaded, but no one can download it. Haven’t found yet any setting to fix this. Anyone can help?

1 лайк

Can you describe the use case? Why is this necessary?

Hi Jeff

Although, now we copy and paste the code in the text section of the post.
Use case: We have a .js file with a kickstarter code or a solution to a recurring problem and we want to share it as an attachment, so that users can download and start using it in their projects.

However, if we change the file extension from .js to .txt, it again shows “The change you wanted was rejected.” (This may be due to some storage optimization on the backend, that if the file has the same content as a previous file, then the new attachment points to the previously uploaded file)
So, I changed the (.txt) extention js file’s content a little bit and uploaded again, and I was able to download the file as attachment.

@codinghorror Is there a security risk in allowing to download .js files?

1 лайк

Yes; we’d need to do some browser research to make sure the file is always downloaded to disk and never executed.

1 лайк

We have a developers forum at fluiggers.com.br, take a look…and we do often share .js files.

1 лайк

Sure, there’s a lot of security issues around allowing js files, so it’s something that we have to take extreme care with.

The Content-Disposition header will prevent execution of downloaded JS files and we are setting it correctly:

attachment; filename="test.js"; filename*=UTF-8''test.js

It works for uploads on S3 and it should work with local uploads as well, but there seems to be a new(ish) security measure from Rails:

ActionController::InvalidCrossOriginRequest (Security warning: an embedded tag on another site requested protected JavaScript. If you know what you’re doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.)

Should be fixable…

3 лайка

I stumbled upon this same issue, we have a coding Q/A forum and need to be able to share big js files for download

I have the same issue in my community. People would like to share JS files but when trying to download them, they get this error:

Excerpt from the rails production log:

Started GET "/uploads/short-url/qDlrltMxEIJ2aYYdt8lZ200E3wA.js" for 94.31.111.247 at 2025-07-09 05:53:30 +0000
Processing by UploadsController#show_short as JS
  Parameters: {"base62"=>"qDlrltMxEIJ2aYYdt8lZ200E3wA", "extension"=>"js"}
Sent file /var/www/discourse/public/uploads/default/original/1X/baab1fc131be960b601467333f5a690b257daeb0.js (0.3ms)
Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.
Completed 422 Unprocessable Entity in 17ms (ActiveRecord: 0.0ms (0 queries, 0 cached) | GC: 0.0ms)

js files are in the list of allowed upload extensions:

Та же проблема у нас. У нас есть JS-файлы, которые работают в нашем собственном программном обеспечении, и ничего, что могло бы когда-либо выполняться в браузере.

Нам удалось исправить проблему с загрузкой в Discourse, перенеся все загрузки в бакет S3 и установив параметр s3_use_cdn_url_for_all_uploads в значение true. Это фактически обходит контроллер коротких ссылок, который, похоже, является главным препятствием для JS-файлов.

Подробности (от моего ИИ, который провёл меня через этот процесс):

  1. Настройка совместимого с S3 хранилища (например, Cloudflare R2)

Discourse не может безопасно отдавать файлы .js с локального диска. Переместите их в бакет.

  • Бакет: Создайте приватный бакет (например, my-discourse-bucket).

  • Ключи API: Сгенерируйте ключ доступа и секретный ключ.

2. Настройка пользовательского домена CDN

В Cloudflare (или у вашего провайдера) подключите пользовательский домен к вашему бакету (например, cdn.example.com). Это гарантирует, что файлы будут отдаваться как статические ресурсы по прямым ссылкам, обходя «страж безопасности» Discourse.

3. Обновление настроек Discourse

В Администрирование → Настройки настройте детали вашего S3. Крайне важно включить следующие параметры, чтобы Discourse не пытался «подписывать» URL временными заголовками, которые могут нарушить работу:

  • s3_use_cdn_url_for_all_uploads: Отметьте этот флажок (это самый важный шаг).

  • s3_cdn_url: Установите значение https://cdn.example.com.

  • s3_region: Используйте us-east-1 (для совместимости с R2).

4. Миграция существующих загрузок (опционально)

Примечание: Это НЕ сработало у нас по неизвестным причинам.

Чтобы исправить старые ссылки в существующих сообщениях, войдите в контейнер и выполните:

Bash

# Внутри /var/discourse
./launcher enter app
rake uploads:migrate_to_s3
rake posts:rebake

Надеюсь, это кому-то поможет.