import re from commia.bearer import get_key, keys from commia.prelude import * from commia.ssh import scp, ssh_args, ssh_prewarm from commia.util import with_written ssh_prewarm("asylum", "secrets@bearer") spacing_pattern = re.compile(r"([;,{}])$") handoff = Path("nginx/handoff.html").read_text().splitlines() handoff = map(lambda line: line.lstrip("\t"), handoff) handoff = map(lambda line: spacing_pattern.sub(r"\1 ", line), handoff) handoff = "".join(handoff).replace('"', '\\"').replace("$", "${dollar}") auth_check = """if ($cookie___proxy_token = "") { return 303 https://$host/.nginx/handoff.html#$request_uri; } auth_request /.nginx/auth;""" auth_locations = ( '''location /.nginx/auth { internal; js_content nginx.validate; } location /.nginx/scopes { internal; proxy_pass http://[::1]:8001/scopes/$arg_token; } location /.nginx/handoff.html { return 200 "''' + handoff + """"; } location /.nginx/cookie { add_header Set-Cookie "__proxy_token=${arg_token}; max-age=${arg_max_age}; path=/; httponly; samesite=lax; secure"; return 200; }""" ) proxy = ( """proxy_http_version 1.1; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade;""" ) domains = get_key(keys.domains).splitlines() terminate_tmpl = Path("nginx/terminate.conf").read_text() terminate = [] for domain in domains: terminate.append(terminate_tmpl.replace("%HOST%", domain)) terminate_indented = "\n".join( map(lambda line: f"\t{line}", "\n".join(terminate).splitlines()) ).strip() nginx_conf = ( Path("nginx/nginx.conf") .read_text() .replace("%AUTH_CHECK%", auth_check) .replace("%AUTH_LOCATIONS%", auth_locations) .replace("%PROXY%", proxy) .replace("%TERMINATE%", terminate_indented) ) with_written( nginx_conf, lambda path: scp(path, "asylum:/etc/nginx/nginx.conf"), ) for name in ["nginx.js", "mime.types", "fastcgi.conf"]: scp(f"nginx/{name}", f"asylum:/etc/nginx/{name}") if run(p([*ssh_args(), "nginx", "-t"])).returncode == 0: run_check(p([*ssh_args(), "systemctl", "restart", "nginx"]))