sovereign-intelligence
Front door to Drake Stapleton's sovereign stack.
Brought by drakestapleton
sovereign-intelligence / docs / archive / drakestapleton.com-old / server / waitlist_api.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Minimal TLS waitlist API with insert-only public behavior.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import json |
| 7 | import os |
| 8 | import re |
| 9 | import sqlite3 |
| 10 | import ssl |
| 11 | import threading |
| 12 | import time |
| 13 | import uuid |
| 14 | from collections import defaultdict, deque |
| 15 | from datetime import datetime, timezone |
| 16 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 17 | from pathlib import Path |
| 18 | |
| 19 | EMAIL_RE = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$") |
| 20 | MAX_BODY_BYTES = 8192 |
| 21 | CONSENT_VERSION = "2026-08-13-v1" |
| 22 | DEFAULT_ORIGINS = { |
| 23 | "https://www.drakestapleton.com", |
| 24 | "https://drakestapleton.com", |
| 25 | } |
| 26 | |
| 27 | |
| 28 | def normalize_email(value: object) -> str: |
| 29 | email = str(value or "").strip().lower() |
| 30 | if len(email) > 254 or not EMAIL_RE.fullmatch(email): |
| 31 | raise ValueError("invalid email") |
| 32 | return email |
| 33 | |
| 34 | |
| 35 | class WaitlistStore: |
| 36 | def __init__(self, path: str): |
| 37 | self.path = path |
| 38 | Path(path).parent.mkdir(parents=True, exist_ok=True) |
| 39 | with self.connect() as connection: |
| 40 | connection.execute( |
| 41 | """ |
| 42 | create table if not exists waitlist_signups ( |
| 43 | id text primary key, |
| 44 | email text not null unique, |
| 45 | consent_version text not null, |
| 46 | created_at text not null |
| 47 | ) |
| 48 | """ |
| 49 | ) |
| 50 | connection.commit() |
| 51 | |
| 52 | def connect(self) -> sqlite3.Connection: |
| 53 | connection = sqlite3.connect(self.path, timeout=5) |
| 54 | connection.execute("pragma journal_mode = wal") |
| 55 | connection.execute("pragma foreign_keys = on") |
| 56 | return connection |
| 57 | |
| 58 | def add(self, email: str, consent_version: str) -> bool: |
| 59 | try: |
| 60 | with self.connect() as connection: |
| 61 | connection.execute( |
| 62 | "insert into waitlist_signups (id, email, consent_version, created_at) values (?, ?, ?, ?)", |
| 63 | ( |
| 64 | str(uuid.uuid4()), |
| 65 | email, |
| 66 | consent_version, |
| 67 | datetime.now(timezone.utc).isoformat(), |
| 68 | ), |
| 69 | ) |
| 70 | connection.commit() |
| 71 | return True |
| 72 | except sqlite3.IntegrityError: |
| 73 | return False |
| 74 | |
| 75 | |
| 76 | class RateLimiter: |
| 77 | def __init__(self, limit: int = 8, window_seconds: int = 3600): |
| 78 | self.limit = limit |
| 79 | self.window_seconds = window_seconds |
| 80 | self.events: dict[str, deque[float]] = defaultdict(deque) |
| 81 | self.lock = threading.Lock() |
| 82 | |
| 83 | def allow(self, key: str) -> bool: |
| 84 | now = time.monotonic() |
| 85 | with self.lock: |
| 86 | events = self.events[key] |
| 87 | while events and now - events[0] > self.window_seconds: |
| 88 | events.popleft() |
| 89 | if len(events) >= self.limit: |
| 90 | return False |
| 91 | events.append(now) |
| 92 | return True |
| 93 | |
| 94 | |
| 95 | def build_handler(store: WaitlistStore, release_marker: str, allowed_origins: set[str]): |
| 96 | limiter = RateLimiter() |
| 97 | |
| 98 | class WaitlistHandler(BaseHTTPRequestHandler): |
| 99 | server_version = "DrakeWaitlist/1" |
| 100 | |
| 101 | def log_message(self, format_string: str, *args: object) -> None: |
| 102 | # Do not log request bodies or email addresses. |
| 103 | super().log_message(format_string, *args) |
| 104 | |
| 105 | def origin(self) -> str | None: |
| 106 | origin = self.headers.get("Origin") |
| 107 | return origin if origin in allowed_origins else None |
| 108 | |
| 109 | def security_headers(self) -> None: |
| 110 | self.send_header("Cache-Control", "no-store") |
| 111 | self.send_header("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'") |
| 112 | self.send_header("Referrer-Policy", "no-referrer") |
| 113 | self.send_header("X-Content-Type-Options", "nosniff") |
| 114 | self.send_header("X-Frame-Options", "DENY") |
| 115 | self.send_header("Strict-Transport-Security", "max-age=31536000") |
| 116 | origin = self.origin() |
| 117 | if origin: |
| 118 | self.send_header("Access-Control-Allow-Origin", origin) |
| 119 | self.send_header("Vary", "Origin") |
| 120 | |
| 121 | def respond(self, status: int, payload: dict[str, object]) -> None: |
| 122 | body = json.dumps(payload, separators=(",", ":")).encode("utf-8") |
| 123 | self.send_response(status) |
| 124 | self.send_header("Content-Type", "application/json; charset=utf-8") |
| 125 | self.send_header("Content-Length", str(len(body))) |
| 126 | self.security_headers() |
| 127 | self.end_headers() |
| 128 | self.wfile.write(body) |
| 129 | |
| 130 | def do_OPTIONS(self) -> None: |
| 131 | if self.path != "/api/signup" or not self.origin(): |
| 132 | self.respond(403, {"ok": False}) |
| 133 | return |
| 134 | self.send_response(204) |
| 135 | self.send_header("Access-Control-Allow-Methods", "POST, OPTIONS") |
| 136 | self.send_header("Access-Control-Allow-Headers", "Content-Type") |
| 137 | self.send_header("Access-Control-Max-Age", "600") |
| 138 | self.security_headers() |
| 139 | self.end_headers() |
| 140 | |
| 141 | def do_GET(self) -> None: |
| 142 | if self.path == "/healthz": |
| 143 | self.respond(200, {"ok": True, "release": release_marker}) |
| 144 | return |
| 145 | self.respond(404, {"ok": False}) |
| 146 | |
| 147 | def do_POST(self) -> None: |
| 148 | if self.path != "/api/signup": |
| 149 | self.respond(404, {"ok": False}) |
| 150 | return |
| 151 | if not self.origin(): |
| 152 | self.respond(403, {"ok": False, "message": "origin not allowed"}) |
| 153 | return |
| 154 | if not limiter.allow(self.client_address[0]): |
| 155 | self.respond(429, {"ok": False, "message": "try again later"}) |
| 156 | return |
| 157 | if self.headers.get_content_type() != "application/json": |
| 158 | self.respond(415, {"ok": False, "message": "json required"}) |
| 159 | return |
| 160 | |
| 161 | try: |
| 162 | length = int(self.headers.get("Content-Length", "0")) |
| 163 | except ValueError: |
| 164 | length = 0 |
| 165 | if length <= 0 or length > MAX_BODY_BYTES: |
| 166 | self.respond(413, {"ok": False, "message": "invalid request size"}) |
| 167 | return |
| 168 | |
| 169 | try: |
| 170 | payload = json.loads(self.rfile.read(length)) |
| 171 | email = normalize_email(payload.get("email")) |
| 172 | if payload.get("consent") is not True: |
| 173 | raise ValueError("consent required") |
| 174 | if payload.get("consentVersion") != CONSENT_VERSION: |
| 175 | raise ValueError("consent version mismatch") |
| 176 | if str(payload.get("website") or ""): |
| 177 | self.respond(202, {"ok": True}) |
| 178 | return |
| 179 | elapsed_ms = int(payload.get("elapsedMs") or 0) |
| 180 | if elapsed_ms < 1200: |
| 181 | self.respond(202, {"ok": True}) |
| 182 | return |
| 183 | except (ValueError, TypeError, json.JSONDecodeError): |
| 184 | self.respond(400, {"ok": False, "message": "invalid signup"}) |
| 185 | return |
| 186 | |
| 187 | store.add(email, CONSENT_VERSION) |
| 188 | # Duplicate and new signups intentionally return the same response. |
| 189 | self.respond(201, {"ok": True}) |
| 190 | |
| 191 | return WaitlistHandler |
| 192 | |
| 193 | |
| 194 | def main() -> None: |
| 195 | host = os.environ.get("WAITLIST_HOST", "0.0.0.0") |
| 196 | port = int(os.environ.get("WAITLIST_PORT", "8443")) |
| 197 | database_path = os.environ.get( |
| 198 | "WAITLIST_DB_PATH", "/var/lib/drake-waitlist/waitlist.sqlite3" |
| 199 | ) |
| 200 | release_marker = os.environ.get("WAITLIST_RELEASE", "development") |
| 201 | origins = { |
| 202 | item.strip() |
| 203 | for item in os.environ.get("WAITLIST_ALLOWED_ORIGINS", "").split(",") |
| 204 | if item.strip() |
| 205 | } or DEFAULT_ORIGINS |
| 206 | |
| 207 | server = ThreadingHTTPServer( |
| 208 | (host, port), build_handler(WaitlistStore(database_path), release_marker, origins) |
| 209 | ) |
| 210 | cert_path = os.environ.get("WAITLIST_CERT_PATH") |
| 211 | key_path = os.environ.get("WAITLIST_KEY_PATH") |
| 212 | if cert_path and key_path: |
| 213 | context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 214 | context.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 215 | context.load_cert_chain(certfile=cert_path, keyfile=key_path) |
| 216 | server.socket = context.wrap_socket(server.socket, server_side=True) |
| 217 | server.serve_forever() |
| 218 | |
| 219 | |
| 220 | if __name__ == "__main__": |
| 221 | main() |