#!/usr/bin/env python3
"""
Serves the Reader-Mode parental-control-bypass POC.

The vulnerable code path requires the page origin to be HTTPS (the
RealizedWebState::RequestPermissionsWithDecisionHandler gate at
web_state_impl_realized_web_state.mm:940-943 denies non-cryptographic,
non-localhost origins before the delegate is consulted). For a real
device test you must therefore serve over HTTPS with a cert the device
trusts. Two options:

  1. Put article.html + gum.html behind any public HTTPS host you control.
  2. Run this script with --tls and install cert.pem as a trusted root
     on the test device (Settings > General > VPN & Device Management).

For iOS Simulator testing against http://localhost the IsOriginLocalhostOrFile
branch passes, so plain HTTP on 127.0.0.1 also works.
"""

import argparse, http.server, os, ssl, sys

class H(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=os.path.dirname(os.path.abspath(__file__)), **kw)
    def end_headers(self):
        self.send_header('Cache-Control', 'no-store')
        super().end_headers()

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--port', type=int, default=8080)
    ap.add_argument('--bind', default='127.0.0.1')
    ap.add_argument('--tls', action='store_true',
                    help='serve HTTPS using ./cert.pem + ./key.pem')
    args = ap.parse_args()

    httpd = http.server.ThreadingHTTPServer((args.bind, args.port), H)
    scheme = 'http'
    if args.tls:
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        ctx.load_cert_chain('cert.pem', 'key.pem')
        httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
        scheme = 'https'
    print(f'serving on {scheme}://{args.bind}:{args.port}/article.html', file=sys.stderr)
    httpd.serve_forever()

if __name__ == '__main__':
    main()
