~cytrogen/masto-fe

ref: 1f141f656dc3fd2b3af5d6edde331bac31bb6526 masto-fe/lib/public_file_server_middleware.rb -rw-r--r-- 1.3 KiB
1f141f65 — Eugen Rochko Change onboarding prompt to use full width of banner in web UI (#26829) 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true

require 'action_dispatch/middleware/static'

class PublicFileServerMiddleware
  SERVICE_WORKER_TTL = 7.days.to_i
  CACHE_TTL          = 28.days.to_i

  def initialize(app)
    @app = app
    @file_handler = ActionDispatch::FileHandler.new(Rails.application.paths['public'].first)
  end

  def call(env)
    file = @file_handler.attempt(env)

    # If the request is not a static file, move on!
    return @app.call(env) if file.nil?

    status, headers, response = file

    # Set cache headers on static files. Some paths require different cache headers
    headers['Cache-Control'] = begin
      request_path = env['REQUEST_PATH']

      if request_path.start_with?('/sw.js')
        "public, max-age=#{SERVICE_WORKER_TTL}, must-revalidate"
      elsif request_path.start_with?(paperclip_root_url)
        "public, max-age=#{CACHE_TTL}, immutable"
      else
        "public, max-age=#{CACHE_TTL}, must-revalidate"
      end
    end

    # Override the default CSP header set by the CSP middleware
    headers['Content-Security-Policy'] = "default-src 'none'; form-action 'none'" if request_path.start_with?(paperclip_root_url)

    headers['X-Content-Type-Options'] = 'nosniff'

    [status, headers, response]
  end

  private

  def paperclip_root_url
    ENV.fetch('PAPERCLIP_ROOT_URL', '/system')
  end
end