public_file_server_middleware.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # frozen_string_literal: true
  2. require 'action_dispatch/middleware/static'
  3. class PublicFileServerMiddleware
  4. SERVICE_WORKER_TTL = 7.days.to_i
  5. CACHE_TTL = 28.days.to_i
  6. def initialize(app)
  7. @app = app
  8. @file_handler = ActionDispatch::FileHandler.new(Rails.application.paths['public'].first)
  9. end
  10. def call(env)
  11. file = @file_handler.attempt(env)
  12. # If the request is not a static file, move on!
  13. return @app.call(env) if file.nil?
  14. status, headers, response = file
  15. # Set cache headers on static files. Some paths require different cache headers
  16. headers['Cache-Control'] = begin
  17. request_path = env['REQUEST_PATH']
  18. if request_path.start_with?('/sw.js')
  19. "public, max-age=#{SERVICE_WORKER_TTL}, must-revalidate"
  20. elsif request_path.start_with?(paperclip_root_url)
  21. "public, max-age=#{CACHE_TTL}, immutable"
  22. else
  23. "public, max-age=#{CACHE_TTL}, must-revalidate"
  24. end
  25. end
  26. # Override the default CSP header set by the CSP middleware
  27. headers['Content-Security-Policy'] = "default-src 'none'; form-action 'none'" if request_path.start_with?(paperclip_root_url)
  28. headers['X-Content-Type-Options'] = 'nosniff'
  29. [status, headers, response]
  30. end
  31. private
  32. def paperclip_root_url
  33. ENV.fetch('PAPERCLIP_ROOT_URL', '/system')
  34. end
  35. end