tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

csp-basic-loader.h2.py (1677B)


      1 import os
      2 
      3 
      4 def _calculate_csp_value(policy, resource_origin):
      5    if policy == "absent":
      6        return None
      7    elif policy == "allowed":
      8        return "script-src 'self' 'unsafe-inline' {}".format(resource_origin)
      9    elif policy == "disallowed":
     10        return "script-src 'self' 'unsafe-inline'"
     11    else:
     12        return None
     13 
     14 
     15 def handle_headers(frame, request, response):
     16    resource_origin = request.GET.first(b"resource-origin").decode()
     17 
     18    # Send a 103 response.
     19    resource_url = request.GET.first(b"resource-url").decode()
     20    link_header_value = "<{}>; rel=preload; as=script".format(resource_url)
     21    early_hints = [
     22        (b":status", b"103"),
     23        (b"link", link_header_value),
     24    ]
     25    early_hints_csp = _calculate_csp_value(
     26        request.GET.first(b"early-hints-policy").decode(), resource_origin)
     27    if early_hints_csp:
     28        early_hints.append((b"content-security-policy", early_hints_csp))
     29    response.writer.write_raw_header_frame(headers=early_hints,
     30                                           end_headers=True)
     31 
     32    # Send the final response header.
     33    response.status = 200
     34    response.headers["content-type"] = "text/html"
     35    final_csp = _calculate_csp_value(
     36        request.GET.first(b"final-policy").decode(), resource_origin)
     37    if final_csp:
     38        response.headers["content-security-policy"] = final_csp
     39    response.write_status_headers()
     40 
     41 
     42 def main(request, response):
     43    current_dir = os.path.dirname(os.path.realpath(__file__))
     44    file_path = os.path.join(current_dir, "csp-basic.html")
     45    with open(file_path, "r") as f:
     46        test_content = f.read()
     47    response.writer.write_data(item=test_content, last=True)