diff mod_strict_https/mod_strict_https.lua @ 5650:0eb2d5ea2428

merge
author Stephen Paul Weber <singpolyma@singpolyma.net>
date Sat, 06 May 2023 19:40:23 -0500
parents f8797e3284ff
children
line wrap: on
line diff
--- a/mod_strict_https/mod_strict_https.lua	Wed Feb 22 22:47:45 2023 -0500
+++ b/mod_strict_https/mod_strict_https.lua	Sat May 06 19:40:23 2023 -0500
@@ -1,44 +1,23 @@
 -- HTTP Strict Transport Security
--- https://tools.ietf.org/html/rfc6797
+-- https://www.rfc-editor.org/info/rfc6797
 
 module:set_global();
 
 local http_server = require "net.http.server";
 
 local hsts_header = module:get_option_string("hsts_header", "max-age=31556952"); -- This means "Don't even try to access without HTTPS for a year"
-
-local _old_send_response;
-local _old_fire_event;
-
-local modules = {};
+local redirect = module:get_option_boolean("hsts_redirect", true);
 
-function module.load()
-	_old_send_response = http_server.send_response;
-	function http_server.send_response(response, body)
-		response.headers.strict_transport_security = hsts_header;
-		return _old_send_response(response, body);
-	end
-
-	_old_fire_event = http_server._events.fire_event;
-	function http_server._events.fire_event(event, payload)
-		local request = payload.request;
-		local host = event:match("^[A-Z]+ ([^/]+)");
-		local module = modules[host];
-		if module and not request.secure then
-			payload.response.headers.location = module:http_url(request.path);
+module:wrap_object_event(http_server._events, false, function(handlers, event_name, event_data)
+	local request, response = event_data.request, event_data.response;
+	if request and response then
+		if request.secure then
+			response.headers.strict_transport_security = hsts_header;
+		elseif redirect then
+			-- This won't get the port number right
+			response.headers.location = "https://" .. request.host .. request.path .. (request.query and "?" .. request.query or "");
 			return 301;
 		end
-		return _old_fire_event(event, payload);
 	end
-end
-function module.unload()
-	http_server.send_response = _old_send_response;
-	http_server._events.fire_event = _old_fire_event;
-end
-function module.add_host(module)
-	local http_host = module:get_option_string("http_host", module.host);
-	modules[http_host] = module;
-	function module.unload()
-		modules[http_host] = nil;
-	end
-end
+	return handlers(event_name, event_data);
+end);