#!/usr/bin/env python3"""An invented site that signs in by an emailed link or the code that link shows(assets/design/chat/SITES.md), for walking Sites on a simulator. Serves onlocalhost:8765. Nothing real: the person, the club and the codes are invented,made fresh at each start, and only ever shown in the page. / signed in: "Signed in as <name>"; else an email form /send "We sent a link", and a box for the code the link shows elsewhere /in?t=... the link, once: signs this browser in (a cookie) and goes home /code?t=... the link opened on another device: shows a code to type there /verify the code typed: signs this browser in /login a user name and password form (any password signs in; none is kept or shown), for filling a login from Secrets"""import html, http.server, secrets, sys, urllib.parsePORT = int(sys.argv[1]) if len(sys.argv) > 1else8765TOKENS = {"walk-link": "kavi@invented.example"} # the dev fixture's mail carries this oneCODES = {} # code -> emailSESSIONS = {} # cookie -> emailTRACKERS = """<!doctype html><meta name=viewport content="width=device-width,initial-scale=1"><title>Tracker test</title><h1>Tracker test</h1><ul id=out></ul><p id=sum>waiting</p><script>const tries = [ ["tracker google-analytics.com", "https://www.google-analytics.com/analytics.js", true], ["tracker doubleclick.net", "https://securepubads.g.doubleclick.net/tag/js/gpt.js", true], ["tracker criteo.net", "https://static.criteo.net/js/ld/publishertag.js", true], ["own host", "/pixel.js?own", false], ["other host, not listed", "http://127.0.0.1:8765/pixel.js?other", false],];let done = 0, blocked = 0, loaded = 0;for (const [name, src, tracker] of tries) { const s = document.createElement("script"); const said = (ok) => { const li = document.createElement("li"); li.textContent = name + ": " + (ok ? "loaded" : "blocked"); out.appendChild(li); if (tracker && !ok) blocked++; if (!tracker && ok) loaded++; if (++done === tries.length) sum.textContent = "trackers blocked " + blocked + " of 3; others loaded " + loaded + " of 2"; }; s.onload = () => said(true); s.onerror = () => said(false); s.src = src; document.head.appendChild(s);}</script>"""PAGE = """<!doctype html><meta name=viewport content="width=device-width,initial-scale=1"><title>Invented Club</title><body style="font:18px -apple-system;margin:24px"><h1>Invented Club</h1>{}</body>"""classSite(http.server.BaseHTTPRequestHandler):def who(self):for part in (self.headers.get("Cookie") or"").split(";"): k, _, v = part.strip().partition("=")if k == "club"and v in SESSIONS:return SESSIONS[v]def raw(self, body, kind): data = body.encode() self.send_response(200) self.send_header("Content-Type", kind) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data)def send(self, body, status=200, headers=()): data = PAGE.format(body).encode() self.send_response(status) self.send_header("Content-Type", "text/html; charset=utf-8")for k, v in headers: self.send_header(k, v) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data)def sign_in(self, email): cookie = secrets.token_hex(16) SESSIONS[cookie] = email self.send_response(302) self.send_header("Set-Cookie", f"club={cookie}; Path=/; Max-Age=31536000; HttpOnly") self.send_header("Location", "/") self.end_headers()def do_GET(self): url = urllib.parse.urlparse(self.path) q = dict(urllib.parse.parse_qsl(url.query))# Trackers measured (IPHONE READY 1): three real tracker scripts on hosts in Sites' list, a script from this# page's own host and one from 127.0.0.1 (another host, not on the list). Each says on the page whether it# loaded; a blocked one errors at once without leaving the phone.if url.path == "/trackers":return self.raw(TRACKERS, "text/html; charset=utf-8")if url.path == "/pixel.js":return self.raw("window.cottonPixel = (window.cottonPixel || 0) + 1;", "text/javascript")if url.path == "/": email = self.who()if email:return self.send(f'<p id=who>Signed in as {html.escape(email)}</p><p><a href="/out">Sign out</a></p>')return self.send('<p>Not signed in.</p><form method=post action=/send><input name=email type=email placeholder=Email>''<button>Email me a link</button></form>')# A link works once, as a real sign-in link does: opened anywhere first, it is spent.if url.path == "/in"and q.get("t") in TOKENS:return self.sign_in(TOKENS.pop(q["t"]))if url.path == "/code"and q.get("t") in TOKENS: code = f"{secrets.randbelow(10**6):06d}" CODES[code] = TOKENS.pop(q["t"])return self.send(f"<p>Type this code where you asked to sign in:</p><p id=code style='font-size:32px'>{code}</p>")if url.path == "/login":return self.send('<p>Sign in</p><form method=post action=/login>''<p><label>Email<br><input name=email type=email autocomplete=username></label></p>''<p><label>Password<br><input name=password type=password autocomplete=current-password></label></p>''<button>Next</button></form>')if url.path == "/out": self.send_response(302) self.send_header("Set-Cookie", "club=; Path=/; Max-Age=0") self.send_header("Location", "/")return self.end_headers() self.send("<p>That link has expired.</p>", 404)def do_POST(self): body = self.rfile.read(int(self.headers.get("Content-Length") or0)).decode() form = dict(urllib.parse.parse_qsl(body))if self.path == "/send": token = secrets.token_hex(8) TOKENS[token] = form.get("email", "") print(f"invented-site: a link was made for /in?t={token} and /code?t={token}", flush=True)return self.send("<p>We sent you a link. If it shows a code instead, type it here.</p>""<form method=post action=/verify><input name=code inputmode=numeric placeholder=Code>""<button>Verify</button></form>")if self.path == "/login"and form.get("email") and form.get("password"):return self.sign_in(form["email"])if self.path == "/verify"and form.get("code") in CODES:return self.sign_in(CODES.pop(form["code"])) self.send("<p>That code is not right.</p>", 400)def log_message(self, *a):passif __name__ == "__main__": print(f"invented-site: http://localhost:{PORT}/", flush=True) http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Site).serve_forever()