diff --git a/etc/mitm_cors.py b/etc/mitm_cors.py index d64c12d..f80761d 100644 --- a/etc/mitm_cors.py +++ b/etc/mitm_cors.py @@ -1,6 +1,6 @@ # Script for mitmproxy, used in ../rundev.sh. Not meant to be run directly. -from mitmproxy import http +from mitmproxy import http, ctx # More information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS @@ -8,6 +8,8 @@ ALLOWED_ORIGINS = ["http://localhost:8000"] ALLOW_HEADERS = "Authorization, *" # Which headers the browser may send EXPOSE_HEADERS = "Authorization, *" # Which headers the browser may expose to scripts +DEFAULT_PORTS = {"http": 80, "https": 443} + def allowed_origin(origin): return origin if origin in ALLOWED_ORIGINS else ALLOWED_ORIGINS[0] @@ -17,10 +19,17 @@ def response(flow): flow.response.headers["Access-Control-Expose-Headers"] = EXPOSE_HEADERS def request(flow): + original_origin = flow.request.headers["Origin"] + + # Spoof Origin, necessary for Mattermost to accept creating a websocket + if original_origin in ALLOWED_ORIGINS: + port_appendix = f":{flow.request.port}" if flow.request.port != DEFAULT_PORTS.get(flow.request.scheme) else "" + flow.request.headers["Origin"] = f"{flow.request.scheme}://{flow.request.host}{port_appendix}"; + # Hijack CORS OPTIONS request if flow.request.method == "OPTIONS": flow.response = http.HTTPResponse.make(200, b"", { - "Access-Control-Allow-Origin": allowed_origin(flow.request.headers["Origin"]), + "Access-Control-Allow-Origin": allowed_origin(original_origin), "Access-Control-Allow-Methods": "GET,POST", "Access-Control-Allow-Headers": ALLOW_HEADERS, "Access-Control-Max-Age": "10"