diff --git a/.env.example b/.env.example index 1d95b4a..f377e73 100644 --- a/.env.example +++ b/.env.example @@ -15,6 +15,14 @@ LUA_VERSION=5.1 GATEWAY_PORT=8080 GATEWAY_LOG_LEVEL=info +# CORS-Konfiguration (comma-separated list) +# Development (default if not set): +# CORS_ALLOWED_ORIGINS=http://localhost:1313,http://127.0.0.1:1313 +# +# Production example: +# CORS_ALLOWED_ORIGINS=https://yourdomain.com,https://www.yourdomain.com +CORS_ALLOWED_ORIGINS=http://localhost:1313,http://127.0.0.1:1313 + # Service-Ports (für lokale Entwicklung) FORMULAR2MAIL_PORT=8081 SAGJAN_PORT=8082 diff --git a/furt-lua/config/server.lua b/furt-lua/config/server.lua index a2916ff..72b3ef0 100644 --- a/furt-lua/config/server.lua +++ b/furt-lua/config/server.lua @@ -9,6 +9,31 @@ return { -- Timeouts (seconds) client_timeout = 10, + -- CORS Configuration + cors = { + -- Default allowed origins for development + -- Override in production with CORS_ALLOWED_ORIGINS environment variable + allowed_origins = (function() + local env_origins = os.getenv("CORS_ALLOWED_ORIGINS") + if env_origins then + -- Parse comma-separated list from environment + local origins = {} + for origin in env_origins:gmatch("([^,]+)") do + table.insert(origins, origin:match("^%s*(.-)%s*$")) -- trim whitespace + end + return origins + else + -- Default development origins + return { + "http://localhost:1313", -- Hugo dev server + "http://127.0.0.1:1313", -- Hugo dev server alternative + "http://localhost:3000", -- Common dev port + "http://127.0.0.1:3000" -- Common dev port alternative + } + end + end)() + }, + -- Logging log_level = "info", log_requests = true, diff --git a/furt-lua/src/main.lua b/furt-lua/src/main.lua index d46e20d..dcda70d 100644 --- a/furt-lua/src/main.lua +++ b/furt-lua/src/main.lua @@ -79,8 +79,40 @@ function FurtServer:parse_request(client) } end +-- Add CORS headers with configurable origins +function FurtServer:add_cors_headers(request) + local allowed_origins = config.cors and config.cors.allowed_origins or { + "http://localhost:1313", + "http://127.0.0.1:1313", + "https://dragons-at-work.de", + "https://www.dragons-at-work.de" + } + + -- Check if request has Origin header + local origin = request and request.headers and request.headers.origin + local cors_origin = "*" -- Default fallback + + -- If origin is provided and in allowed list, use it + if origin then + for _, allowed in ipairs(allowed_origins) do + if origin == allowed then + cors_origin = origin + break + end + end + end + + return { + ["Access-Control-Allow-Origin"] = cors_origin, + ["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS", + ["Access-Control-Allow-Headers"] = "Content-Type, X-API-Key, Authorization, Accept", + ["Access-Control-Max-Age"] = "86400", + ["Access-Control-Allow-Credentials"] = "false" + } +end + -- Create HTTP response -function FurtServer:create_response(status, data, content_type) +function FurtServer:create_response(status, data, content_type, additional_headers, request) content_type = content_type or "application/json" local body = "" @@ -90,19 +122,30 @@ function FurtServer:create_response(status, data, content_type) body = tostring(data or "") end - local response = string.format( - "HTTP/1.1 %d %s\r\n" .. - "Content-Type: %s\r\n" .. - "Content-Length: %d\r\n" .. - "Connection: close\r\n" .. - "Server: Furt-Lua/1.0\r\n" .. - "\r\n%s", - status, - self:get_status_text(status), - content_type, - #body, - body - ) + -- Start with CORS headers + local headers = self:add_cors_headers(request) + + -- Add standard headers + headers["Content-Type"] = content_type + headers["Content-Length"] = tostring(#body) + headers["Connection"] = "close" + headers["Server"] = "Furt-Lua/1.0" + + -- Add additional headers if provided + if additional_headers then + for key, value in pairs(additional_headers) do + headers[key] = value + end + end + + -- Build response + local response = string.format("HTTP/1.1 %d %s\r\n", status, self:get_status_text(status)) + + for key, value in pairs(headers) do + response = response .. key .. ": " .. value .. "\r\n" + end + + response = response .. "\r\n" .. body return response end @@ -111,6 +154,7 @@ end function FurtServer:get_status_text(status) local status_texts = { [200] = "OK", + [204] = "No Content", [400] = "Bad Request", [404] = "Not Found", [405] = "Method Not Allowed", @@ -123,7 +167,7 @@ end function FurtServer:handle_client(client) local request = self:parse_request(client) if not request then - local response = self:create_response(400, {error = "Invalid request"}) + local response = self:create_response(400, {error = "Invalid request"}, nil, nil, nil) client:send(response) return end @@ -131,6 +175,13 @@ function FurtServer:handle_client(client) print(string.format("[%s] %s %s", os.date("%Y-%m-%d %H:%M:%S"), request.method, request.path)) + -- Handle OPTIONS preflight requests (CORS) + if request.method == "OPTIONS" then + local response = self:create_response(204, "", "text/plain", nil, request) + client:send(response) + return + end + -- Route handling local handler = nil if self.routes[request.method] and self.routes[request.method][request.path] then @@ -143,11 +194,12 @@ function FurtServer:handle_client(client) client:send(result) else print("Handler error: " .. tostring(result)) - local error_response = self:create_response(500, {error = "Internal server error"}) + local error_response = self:create_response(500, {error = "Internal server error"}, nil, nil, request) client:send(error_response) end else - local response = self:create_response(404, {error = "Route not found"}) + print("Route not found: " .. request.method .. " " .. request.path) + local response = self:create_response(404, {error = "Route not found", method = request.method, path = request.path}, nil, nil, request) client:send(response) end end @@ -160,6 +212,7 @@ function FurtServer:start() end print(string.format("Furt HTTP-Server started on %s:%d", self.host, self.port)) + print("CORS enabled for all origins") print("Press Ctrl+C to stop") while true do @@ -184,7 +237,7 @@ server:add_route("GET", "/health", function(request) timestamp = os.time(), smtp_configured = config.mail and config.mail.username ~= nil } - return server:create_response(200, response_data) + return server:create_response(200, response_data, nil, nil, request) end) -- Test route for development @@ -200,28 +253,31 @@ server:add_route("POST", "/test", function(request) response_data.headers_count = response_data.headers_count + 1 end - return server:create_response(200, response_data) + return server:create_response(200, response_data, nil, nil, request) end) -- Mail service route (placeholder for Week 1) server:add_route("POST", "/v1/mail/send", function(request) + print("Mail endpoint called - Method: " .. request.method .. ", Path: " .. request.path) + -- Basic validation if not request.body or request.body == "" then - return server:create_response(400, {error = "No request body"}) + return server:create_response(400, {error = "No request body"}, nil, nil, request) end -- Try to parse JSON local success, data = pcall(cjson.decode, request.body) if not success then - return server:create_response(400, {error = "Invalid JSON"}) + return server:create_response(400, {error = "Invalid JSON", body = request.body}, nil, nil, request) end -- Basic field validation if not data.name or not data.email or not data.message then return server:create_response(400, { error = "Missing required fields", - required = {"name", "email", "message"} - }) + required = {"name", "email", "message"}, + received = data + }, nil, nil, request) end -- Send email via SMTP @@ -237,9 +293,18 @@ server:add_route("POST", "/v1/mail/send", function(request) config.mail.to_address, subject, email_content, data.name) if success then - return server:create_response(200, {success = true, message = "Mail sent", request_id = request_id}) + return server:create_response(200, { + success = true, + message = "Mail sent successfully", + request_id = request_id + }, nil, nil, request) else - return server:create_response(500, {success = false, error = result, request_id = request_id}) + print("SMTP Error: " .. tostring(result)) + return server:create_response(500, { + success = false, + error = "Failed to send email: " .. tostring(result), + request_id = request_id + }, nil, nil, request) end end)