From 2596410b97d1328d942229e9742c60448c32d5eb Mon Sep 17 00:00:00 2001 From: Omar Roth Date: Fri, 9 Mar 2018 13:22:04 -0600 Subject: [PATCH] Add HTTP redirect --- config/config.yml | 3 ++- src/helpers.cr | 1 + src/invidious.cr | 24 ++++++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/config/config.yml b/config/config.yml index f8a06faa..8ff5e990 100644 --- a/config/config.yml +++ b/config/config.yml @@ -5,4 +5,5 @@ db: password: kemal host: localhost port: 5432 - dbname: invidious \ No newline at end of file + dbname: invidious +redirect: false \ No newline at end of file diff --git a/src/helpers.cr b/src/helpers.cr index 7ca5bd61..88bb576e 100644 --- a/src/helpers.cr +++ b/src/helpers.cr @@ -24,6 +24,7 @@ class Config port: Int32, dbname: String, ), + redirect: Bool }) end diff --git a/src/invidious.cr b/src/invidious.cr index 1474fa40..9e4c3408 100644 --- a/src/invidious.cr +++ b/src/invidious.cr @@ -25,6 +25,7 @@ CONFIG = Config.from_yaml(File.read("config/config.yml")) pool_size = CONFIG.pool_size threads = CONFIG.threads +redirect = CONFIG.redirect Kemal.config.extra_options do |parser| parser.banner = "Usage: invidious [arguments]" @@ -44,6 +45,16 @@ Kemal.config.extra_options do |parser| exit end end + parser.on("-r REDIRECT", "--redirect=BOOL", "Whether insecure requests should be forced to HTTPS, requires -s (default #{redirect})") do |boolean| + if boolean == "true" + redirect = true + elsif boolean == "false" + redirect = false + else + puts "REDIRECT must be 'true' or 'false'" + exit + end + end end Kemal::CLI.new @@ -327,6 +338,19 @@ error 500 do |env| templated "error" end +# Add redirect if SSL is enabled and redirect is enabled +if Kemal.config.ssl && redirect + spawn do + server = HTTP::Server.new("0.0.0.0", 80) do |context| + context.response.headers.add "Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload" + context.response.headers.add "Location", "https://#{context.request.headers["Host"]}" + context.response.status_code = 302 + end + + server.listen + end +end + static_headers do |response, filepath, filestat| response.headers.add("Cache-Control", "max-age=86400") end