Files
rotatyvote/rotatyvote/app.py
T

897 lines
33 KiB
Python

import asyncio
import contextlib
import json
import logging
from dataclasses import dataclass, field
from pathlib import Path
from urllib.parse import urlsplit
import segno
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import FileResponse, JSONResponse, RedirectResponse, Response
from starlette.routing import Mount, Route, WebSocketRoute
from starlette.staticfiles import StaticFiles
from starlette.websockets import WebSocket, WebSocketDisconnect
from . import config, ringcode
from .db import DB, open_db
from .tokens import check_key, current_slot, make_token, new_key, now_ms, sha, verify_token
log = logging.getLogger("rotatyvote")
STATIC = Path(__file__).resolve().parent.parent / "static"
MAX_BODY = 64 * 1024
db: DB | None = None
@dataclass
class Attempt:
slots: set = field(default_factory=set)
first_ms: int = 0
last_ms: int = 0
presence_ms: int = 0
code_tries: int = 0
attempts: dict[tuple[str, str], Attempt] = {}
def prune_attempts():
cutoff = now_ms() - 15 * 60 * 1000
for k in [k for k, a in attempts.items() if a.last_ms < cutoff]:
del attempts[k]
def clear_attempts(pid):
for k in [k for k in attempts if k[0] == pid]:
del attempts[k]
def q_public(q, with_results: bool):
d = {
"id": q["id"], "text": q["text"], "kind": q["kind"], "options": json.loads(q["options"]),
"max_choices": q["max_choices"], "allow_blank": bool(q["allow_blank"]), "state": q["state"],
"results_public": bool(q["results_public"]), "participants": db.participants(q["id"]),
}
# nobody, admin included, sees tallies while a question is open
if with_results and q["state"] == "closed":
d["results"] = db.results(q)
return d
def admin_state(pid):
p = db.poll(pid)
return {
"type": "state",
"poll": {
"id": p["id"], "title": p["title"], "interval_ms": p["interval_ms"],
"scans_required": p["scans_required"], "enrollment_open": bool(p["enrollment_open"]),
"max_voters": p["max_voters"], "expected": p["expected"],
"require_code": bool(p["require_code"]), "focus_qid": p["focus_qid"],
"vote_scans": p["vote_scans"], "code_style": p["code_style"],
},
"voters": db.voter_count(pid),
"codes": codes_summary(pid),
"questions": [q_public(q, True) for q in db.questions(pid)],
"screens": len(hub.screens.get(pid, ())),
"public_url": config.PUBLIC_URL,
}
def codes_summary(pid):
rows = db.codes(pid)
out = {}
for kind, flag in (("access", 0), ("rescue", 1)):
sel = [r for r in rows if r["rescue"] == flag]
out[kind] = {"total": len(sel), "used": sum(r["used"] for r in sel)}
return out
def has_open_question(pid):
return db.one("SELECT 1 FROM questions WHERE poll_id=? AND state='open'", pid) is not None
def presence_check(p):
"""qr must stay on screen while a vote needs proof of presence.
code holders are exempt, so no qr if everyone came in with a code"""
return (p["vote_scans"] > 0 and has_open_question(p["id"])
and db.one("SELECT 1 FROM voters WHERE poll_id=? AND via_code=0", p["id"]) is not None)
def needs_qr(p):
return bool(p["enrollment_open"]) or presence_check(p)
def screen_state(pid):
p = db.poll(pid)
focus = None
if p["focus_qid"]:
q = db.question(pid, p["focus_qid"])
if q and q["state"] != "draft":
focus = q_public(q, bool(q["results_public"]))
return {
"type": "state", "title": p["title"], "enrollment_open": bool(p["enrollment_open"]),
"voters": db.voter_count(pid), "expected": p["expected"], "max_voters": p["max_voters"],
"scans_required": p["scans_required"], "interval_ms": p["interval_ms"], "focus": focus,
"presence": presence_check(p), "vote_scans": p["vote_scans"], "code_style": p["code_style"],
}
def voter_state(pid, voter):
p = db.poll(pid)
voted = db.voted_qids(voter["id"], pid)
qs = []
for q in db.questions(pid):
if q["state"] == "open" or (q["state"] == "closed" and q["results_public"]):
d = q_public(q, bool(q["results_public"]))
d["voted"] = q["id"] in voted
qs.append(d)
scans = 0 if voter["via_code"] else p["vote_scans"]
return {"type": "state", "title": p["title"], "enrolled": True, "questions": qs, "vote_scans": scans,
"code_style": p["code_style"]}
def qr_modules(url: str, error="m"):
qr = segno.make(url, error=error, micro=False)
return ["".join("1" if b else "0" for b in row) for row in qr.matrix]
def entry_qr(base: str, pid: str):
"""static qr shown in a corner of the ring-code projector: opens the voting page from the camera app.
upper case keeps it in qr alphanumeric mode, a smaller symbol (/V/ redirects to /v/)"""
url = f"{base}/V/{pid}".upper()
return {"type": "entry", "modules": qr_modules(url, error="l"), "url": f"{base}/v/{pid}"}
def resolve_token(p, tok: str, grace_ms: int):
"""full slot for a fresh, authentic token in either format (qr 'slot.mac' or ring 'r<s16>.<mac>'), else None"""
if tok.startswith("r"):
iv, now = p["interval_ms"], now_ms()
slot = ringcode.resolve(p["secret"], p["id"], iv, tok, current_slot(iv, now), (iv + grace_ms) // iv + 1)
if slot is None or not 0 <= now - slot * iv <= iv + grace_ms:
return None
return slot
return verify_token(p["secret"], p["id"], p["interval_ms"], tok, grace_ms)
class Hub:
def __init__(self):
self.screens: dict[str, dict[WebSocket, str]] = {} # ws -> origin
self.admins: dict[str, set[WebSocket]] = {}
self.voters: dict[str, dict[str, set[WebSocket]]] = {}
self.tickers: dict[str, asyncio.Task] = {}
self.pending: dict[str, bool] = {}
async def send(self, ws: WebSocket, msg):
# a stalled peer (half-open tcp behind a proxy) must not block everyone else
try:
await asyncio.wait_for(ws.send_text(json.dumps(msg, ensure_ascii=False)), 5)
except Exception:
self.drop(ws)
def drop(self, ws: WebSocket):
for group in self.screens.values():
group.pop(ws, None)
for group in self.admins.values():
group.discard(ws)
for group in self.voters.values():
for conns in group.values():
conns.discard(ws)
async def send_all(self, conns, msg):
await asyncio.gather(*[self.send(ws, msg) for ws in list(conns)])
def refresh(self, pid, voters=False):
"""debounced push of fresh state to admins + screens (+ every voter)"""
if pid in self.pending:
self.pending[pid] = self.pending[pid] or voters
return
self.pending[pid] = voters
asyncio.get_running_loop().create_task(self._flush(pid))
async def _flush(self, pid):
await asyncio.sleep(0.12)
voters = self.pending.pop(pid, False)
if not db.poll(pid):
return
if self.admins.get(pid):
await self.send_all(self.admins[pid], admin_state(pid))
if self.screens.get(pid):
await self.send_all(self.screens[pid], screen_state(pid))
if voters:
for vid in list(self.voters.get(pid, {})):
await self.push_voter(pid, vid)
self.ensure_ticker(pid)
async def push_voter(self, pid, vid):
conns = self.voters.get(pid, {}).get(vid)
if not conns:
return
v = db.one("SELECT * FROM voters WHERE id=?", vid)
if not v:
return
await self.send_all(conns, voter_state(pid, v))
def ensure_ticker(self, pid):
t = self.tickers.get(pid)
if t and not t.done():
return
p = db.poll(pid)
if p and needs_qr(p) and self.screens.get(pid):
self.tickers[pid] = asyncio.get_running_loop().create_task(self._tick(pid))
async def _tick(self, pid):
try:
while True:
p = db.poll(pid)
screens = self.screens.get(pid)
if not p or not needs_qr(p) or not screens:
return
iv = p["interval_ms"]
slot = current_slot(iv)
if p["code_style"] == "ring":
# the screen draws the rings itself, it only needs the bits for this slot
await self.send_all(screens, {
"type": "ring", "bits": ringcode.render_bits(p["secret"], pid, iv, slot),
"token": ringcode.token(p["secret"], pid, iv, slot), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv})
await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000))
continue
token = make_token(p["secret"], pid, iv, slot)
by_origin: dict[str, list[WebSocket]] = {}
for ws, origin in list(screens.items()):
by_origin.setdefault(config.PUBLIC_URL or origin, []).append(ws)
for base, conns in by_origin.items():
url = f"{base}/v/{pid}#{token}"
msg = {"type": "qr", "url": url, "token": token, "modules": qr_modules(url), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv}
await self.send_all(conns, msg)
await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000))
except asyncio.CancelledError:
pass
except Exception:
log.exception("ticker crashed for %s", pid)
hub = Hub()
async def heartbeat():
# proxies (cloudflare ~100s) drop idle websockets, keep every socket chatty
while True:
await asyncio.sleep(config.HEARTBEAT_S)
try:
conns = [ws for group in hub.screens.values() for ws in group]
conns += [ws for group in hub.admins.values() for ws in group]
conns += [ws for group in hub.voters.values() for s in group.values() for ws in s]
await hub.send_all(conns, {"type": "ping"})
except Exception:
log.exception("heartbeat")
async def body(request: Request) -> dict:
raw = await request.body()
if len(raw) > MAX_BODY:
raise HTTPException(413)
if not raw:
return {}
try:
data = json.loads(raw)
except ValueError:
raise HTTPException(400, "invalid json")
if not isinstance(data, dict):
raise HTTPException(400, "invalid json")
return data
def err(code: str, status=400):
return JSONResponse({"error": code}, status_code=status)
def get_poll(pid):
p = db.poll(pid)
if not p:
raise HTTPException(404, "poll not found")
return p
def require_admin(request: Request, pid):
p = get_poll(pid)
auth = request.headers.get("authorization", "")
key = auth[7:] if auth.lower().startswith("bearer ") else None
if not check_key(key, p["admin_hash"]):
raise HTTPException(403, "bad admin key")
return p
def voter_cookie(pid):
return f"rv_{pid}"
def attempt_cookie(pid):
return f"rva_{pid}"
def current_voter(request_or_ws, pid):
return db.voter_by_cred(pid, request_or_ws.cookies.get(voter_cookie(pid)))
def set_cookie(resp: Response, name, value, max_age):
resp.set_cookie(name, value, max_age=max_age, httponly=True, samesite="strict",
secure=config.SECURE_COOKIES, path="/")
def public_host(conn) -> str:
# proxies often rewrite Host, the forwarded one is what the browser used
if config.BEHIND_PROXY and conn.headers.get("x-forwarded-host"):
return conn.headers["x-forwarded-host"].split(",")[0].strip()
return conn.headers.get("host", "")
def same_origin(ws: WebSocket) -> bool:
origin = ws.headers.get("origin")
if not origin:
return False
allowed = {ws.headers.get("host"), public_host(ws)}
if config.PUBLIC_URL:
allowed.add(urlsplit(config.PUBLIC_URL).netloc)
return urlsplit(origin).netloc in allowed
def clamp_int(v, lo, hi, name):
try:
v = int(v)
except (TypeError, ValueError):
raise HTTPException(400, f"invalid {name}")
if not lo <= v <= hi:
raise HTTPException(400, f"{name} out of range")
return v
def opt_int(v, lo, hi, name):
if v in (None, "", 0):
return None
return clamp_int(v, lo, hi, name)
def parse_question(d: dict):
text = str(d.get("text", "")).strip()
if not 1 <= len(text) <= 500:
raise HTTPException(400, "question text required (max 500)")
kind = d.get("kind", "single")
if kind not in ("single", "multi"):
raise HTTPException(400, "invalid kind")
opts = d.get("options")
if not isinstance(opts, list):
raise HTTPException(400, "options must be a list")
opts = [str(o).strip() for o in opts if str(o).strip()]
if not 2 <= len(opts) <= 50 or any(len(o) > 200 for o in opts):
raise HTTPException(400, "2 to 50 options, 200 chars max each")
if len(set(opts)) != len(opts):
raise HTTPException(400, "duplicate options")
max_choices = 1 if kind == "single" else clamp_int(d.get("max_choices", len(opts)), 1, len(opts), "max_choices")
allow_blank = bool(d.get("allow_blank", True))
return text, kind, opts, max_choices, allow_blank
def page(name):
async def handler(request: Request):
if "pid" in request.path_params:
get_poll(request.path_params["pid"])
return FileResponse(STATIC / name)
return handler
async def public_config(request: Request):
return JSONResponse({"create_password": bool(config.CREATE_PASSWORD), "public_url": config.PUBLIC_URL})
async def create_poll(request: Request):
d = await body(request)
if config.CREATE_PASSWORD and not check_key(d.get("password"), _create_hash):
return err("bad_password", 403)
title = str(d.get("title", "")).strip()
if not 1 <= len(title) <= 200:
return err("title_required")
interval = clamp_int(d.get("interval_ms", 1000), config.MIN_INTERVAL_MS, config.MAX_INTERVAL_MS, "interval_ms")
scans = clamp_int(d.get("scans_required", 5), config.MIN_SCANS, config.MAX_SCANS, "scans_required")
expected = opt_int(d.get("expected"), 1, 100000, "expected")
max_voters = opt_int(d.get("max_voters"), 1, 100000, "max_voters")
vote_scans = clamp_int(d.get("vote_scans", config.DEFAULT_VOTE_SCANS), 0, config.MAX_VOTE_SCANS, "vote_scans")
code_style = d.get("code_style", "ring")
if code_style not in ("ring", "qr"):
return err("bad_code_style")
questions = [parse_question(q) for q in (d.get("questions") or [])]
pid, admin_key, screen_key = db.create_poll(title, interval, scans, bool(d.get("require_code")),
expected, max_voters, vote_scans, code_style)
for q in questions:
db.add_question(pid, *q)
codes = int(d.get("codes") or 0)
if d.get("require_code") and codes:
db.add_codes(pid, clamp_int(codes, 1, 5000, "codes"))
return JSONResponse({"id": pid, "admin_key": admin_key, "screen_key": screen_key})
async def create_trial(request: Request):
# no password even when creation is locked: a trial only enrolls, nobody gets its admin key
db.purge_trials(config.TRIAL_TTL_MS)
if db.trial_count() >= config.MAX_TRIALS:
return err("too_many_trials", 429)
pid, _, screen_key = db.create_poll("Essai", 500, 5, False, None, 200, config.DEFAULT_VOTE_SCANS, "ring",
trial=True)
db.add_question(pid, "Le vote d'essai fonctionne ?", "single", ["Oui", "Non"], 1, False)
db.update_poll(pid, enrollment_open=1)
return JSONResponse({"id": pid, "screen_key": screen_key})
async def admin_get(request: Request):
pid = request.path_params["pid"]
require_admin(request, pid)
return JSONResponse(admin_state(pid))
async def admin_patch(request: Request):
pid = request.path_params["pid"]
p = require_admin(request, pid)
d = await body(request)
upd = {}
if "title" in d:
t = str(d["title"]).strip()
if not 1 <= len(t) <= 200:
return err("title_required")
upd["title"] = t
if "interval_ms" in d:
upd["interval_ms"] = clamp_int(d["interval_ms"], config.MIN_INTERVAL_MS, config.MAX_INTERVAL_MS, "interval_ms")
if "scans_required" in d:
upd["scans_required"] = clamp_int(d["scans_required"], config.MIN_SCANS, config.MAX_SCANS, "scans_required")
if "enrollment_open" in d:
upd["enrollment_open"] = int(bool(d["enrollment_open"]))
if "max_voters" in d:
upd["max_voters"] = opt_int(d["max_voters"], 1, 100000, "max_voters")
if "expected" in d:
upd["expected"] = opt_int(d["expected"], 1, 100000, "expected")
if "require_code" in d:
upd["require_code"] = int(bool(d["require_code"]))
if "code_style" in d:
if d["code_style"] not in ("ring", "qr"):
return err("bad_code_style")
upd["code_style"] = d["code_style"]
if "vote_scans" in d:
upd["vote_scans"] = clamp_int(d["vote_scans"], 0, config.MAX_VOTE_SCANS, "vote_scans")
if "focus_qid" in d:
fq = d["focus_qid"]
if fq is not None and not db.question(pid, fq):
return err("unknown_question")
upd["focus_qid"] = fq
db.update_poll(pid, **upd)
if any(k in upd for k in ("interval_ms", "scans_required", "require_code")) or upd.get("enrollment_open") == 0:
# rules changed mid-way: half-done attempts start over
clear_attempts(pid)
hub.refresh(pid, voters=True)
return JSONResponse({"ok": True})
async def admin_rotate_screen_key(request: Request):
pid = request.path_params["pid"]
require_admin(request, pid)
key = new_key()
db.c.execute("UPDATE polls SET screen_hash=? WHERE id=?", (sha(key), pid))
for ws in list(hub.screens.get(pid, {})):
await ws.close(code=4001)
return JSONResponse({"screen_key": key})
async def admin_add_question(request: Request):
pid = request.path_params["pid"]
p = require_admin(request, pid)
d = await body(request)
qid = db.add_question(pid, *parse_question(d))
if d.get("open"):
db.set_question(qid, state="open")
db.update_poll(pid, focus_qid=qid)
hub.refresh(pid, voters=bool(d.get("open")))
return JSONResponse({"id": qid})
async def admin_question_action(request: Request):
pid = request.path_params["pid"]
qid = int(request.path_params["qid"])
action = request.path_params["action"]
p = require_admin(request, pid)
q = db.question(pid, qid)
if not q:
return err("unknown_question", 404)
st = q["state"]
if action == "open":
if st != "draft":
return err("not_draft")
db.set_question(qid, state="open")
db.update_poll(pid, focus_qid=qid)
elif action == "close":
if st != "open":
return err("not_open")
db.set_question(qid, state="closed")
elif action in ("publish", "unpublish"):
if st != "closed":
return err("not_closed")
db.set_question(qid, results_public=int(action == "publish"))
if action == "publish":
db.update_poll(pid, focus_qid=qid)
elif action == "focus":
db.update_poll(pid, focus_qid=qid)
elif action == "delete":
if st != "draft":
return err("not_draft")
db.delete_question(qid)
if p["focus_qid"] == qid:
db.update_poll(pid, focus_qid=None)
else:
return err("unknown_action", 404)
hub.refresh(pid, voters=True)
return JSONResponse({"ok": True})
async def admin_codes(request: Request):
pid = request.path_params["pid"]
require_admin(request, pid)
if request.method == "POST":
d = await body(request)
db.add_codes(pid, clamp_int(d.get("count"), 1, 5000, "count"), rescue=bool(d.get("rescue")))
hub.refresh(pid)
return JSONResponse({"codes": db.codes(pid)})
async def admin_export(request: Request):
pid = request.path_params["pid"]
p = require_admin(request, pid)
out = {
"poll": {"id": pid, "title": p["title"], "voters_enrolled": db.voter_count(pid)},
"questions": [],
}
for q in db.questions(pid):
d = q_public(q, True)
if q["state"] == "closed":
d["ballots"] = db.ballots(q["id"])
out["questions"].append(d)
return JSONResponse(out, headers={"content-disposition": f'attachment; filename="rotatyvote-{pid}.json"'})
async def voter_me(request: Request):
pid = request.path_params["pid"]
p = get_poll(pid)
v = current_voter(request, pid)
if v:
return JSONResponse(voter_state(pid, v))
a = attempts.get((pid, request.cookies.get(attempt_cookie(pid), "")))
presence = bool(a and a.presence_ms and now_ms() - a.presence_ms < config.CODE_ENTRY_TTL_S * 1000)
return JSONResponse({
"type": "state", "title": p["title"], "enrolled": False,
"enrollment_open": bool(p["enrollment_open"]), "scans_required": p["scans_required"],
"require_code": bool(p["require_code"]), "need_code": presence and bool(p["require_code"]),
"code_style": p["code_style"],
"count": len(a.slots) if a else 0,
})
def _finish_enroll(pid, att_id, code=None):
cred, e = db.enroll(pid, code)
if e:
return None, e
attempts.pop((pid, att_id), None)
resp = JSONResponse({"status": "enrolled"})
set_cookie(resp, voter_cookie(pid), cred, 7 * 24 * 3600)
resp.delete_cookie(attempt_cookie(pid), path="/")
# a trial has no admin: the first enrolled phone opens the sample question so the vote can be tried too
p = db.poll(pid)
if p["trial"] and not p["focus_qid"]:
q = next((q for q in db.questions(pid) if q["state"] == "draft"), None)
if q:
db.set_question(q["id"], state="open")
db.update_poll(pid, focus_qid=q["id"])
hub.refresh(pid, voters=True)
return resp, None
async def voter_scan(request: Request):
pid = request.path_params["pid"]
p = get_poll(pid)
d = await body(request)
if current_voter(request, pid):
return JSONResponse({"status": "enrolled"})
if not p["enrollment_open"]:
return JSONResponse({"status": "closed"})
if len(attempts) > 50000:
prune_attempts()
att_id = request.cookies.get(attempt_cookie(pid))
fresh_cookie = None
if not att_id or (pid, att_id) not in attempts:
att_id = new_key()
fresh_cookie = att_id
attempts[(pid, att_id)] = Attempt()
a = attempts[(pid, att_id)]
now = now_ms()
a.last_ms = now
required = p["scans_required"]
window = required * p["interval_ms"] + config.ATTEMPT_SLACK_MS
if a.presence_ms:
if now - a.presence_ms > config.CODE_ENTRY_TTL_S * 1000:
a.slots.clear(); a.first_ms = 0; a.presence_ms = 0
elif a.first_ms and now - a.first_ms > window:
a.slots.clear(); a.first_ms = 0
status = "progress"
slot = resolve_token(p, str(d.get("token", ""))[:64], config.TOKEN_GRACE_MS)
accepted = False
if slot is not None and not a.presence_ms and slot not in a.slots:
if not a.first_ms:
a.first_ms = now
a.slots.add(slot)
accepted = True
if len(a.slots) >= required and not a.presence_ms:
a.presence_ms = now
if a.presence_ms:
if p["require_code"]:
status = "need_code"
else:
resp, e = _finish_enroll(pid, att_id)
if resp:
return resp
status = e
resp = JSONResponse({"status": status, "count": min(len(a.slots), required), "required": required,
"accepted": accepted, "valid": slot is not None})
if fresh_cookie:
set_cookie(resp, attempt_cookie(pid), fresh_cookie, 900)
return resp
async def voter_rescue(request: Request):
"""enrollment with a one-time rescue code, for phones whose camera can't scan"""
pid = request.path_params["pid"]
get_poll(pid)
d = await body(request)
if current_voter(request, pid):
return JSONResponse({"status": "enrolled"})
cred, e = db.enroll(pid, rescue_code=str(d.get("code", ""))[:32])
if e:
return JSONResponse({"status": e})
resp = JSONResponse({"status": "enrolled"})
set_cookie(resp, voter_cookie(pid), cred, 7 * 24 * 3600)
hub.refresh(pid)
return resp
async def voter_code(request: Request):
pid = request.path_params["pid"]
p = get_poll(pid)
d = await body(request)
if current_voter(request, pid):
return JSONResponse({"status": "enrolled"})
att_id = request.cookies.get(attempt_cookie(pid), "")
a = attempts.get((pid, att_id))
if not a or not a.presence_ms or now_ms() - a.presence_ms > config.CODE_ENTRY_TTL_S * 1000:
return JSONResponse({"status": "rescan"})
a.code_tries += 1
if a.code_tries > 5:
attempts.pop((pid, att_id), None)
return JSONResponse({"status": "rescan"})
resp, e = _finish_enroll(pid, att_id, str(d.get("code", ""))[:32])
if resp:
return resp
return JSONResponse({"status": e, "tries_left": 5 - a.code_tries})
async def voter_vote(request: Request):
pid = request.path_params["pid"]
get_poll(pid)
v = current_voter(request, pid)
if not v:
return err("not_enrolled", 403)
d = await body(request)
try:
qid = int(d.get("question_id"))
except (TypeError, ValueError):
return err("bad_question")
q = db.question(pid, qid)
if not q:
return err("bad_question", 404)
choices = d.get("choices")
if not isinstance(choices, list) or not all(isinstance(c, int) and not isinstance(c, bool) for c in choices):
return err("bad_choices")
n_opts = len(json.loads(q["options"]))
if len(set(choices)) != len(choices) or any(not 0 <= c < n_opts for c in choices):
return err("bad_choices")
if not choices and not q["allow_blank"]:
return err("blank_not_allowed")
if len(choices) > q["max_choices"]:
return err("too_many_choices")
p = db.poll(pid)
need = 0 if v["via_code"] else p["vote_scans"]
if need:
# proof of presence at vote time: fresh distinct codes read off the projector.
# checked then dropped, nothing about them is stored next to the ballot
tokens = d.get("presence")
if not isinstance(tokens, list):
return err("presence_required")
window = config.TOKEN_GRACE_MS + need * p["interval_ms"]
slots = {resolve_token(p, str(t)[:64], window) for t in tokens[:20]}
slots.discard(None)
if len(slots) < need:
return err("presence_required")
e = db.cast(pid, qid, v["id"], choices)
if e:
return err(e, 409)
hub.refresh(pid)
await hub.push_voter(pid, v["id"])
return JSONResponse({"ok": True})
async def _auth_first_message(ws: WebSocket, ok) -> bool:
try:
msg = json.loads(await asyncio.wait_for(ws.receive_text(), 5))
except Exception:
return False
return ok(msg.get("key"))
async def _hold(ws: WebSocket):
try:
while True:
await ws.receive_text()
except WebSocketDisconnect:
pass
except Exception:
pass
async def ws_screen(ws: WebSocket):
pid = ws.path_params["pid"]
p = db.poll(pid)
await ws.accept()
if not p or not await _auth_first_message(
ws, lambda k: check_key(k, p["screen_hash"]) or check_key(k, p["admin_hash"])):
await ws.close(code=4003)
return
scheme = "https" if ws.url.scheme == "wss" or config.BEHIND_PROXY else "http"
origin = f"{scheme}://{public_host(ws)}"
hub.screens.setdefault(pid, {})[ws] = origin
await hub.send(ws, entry_qr(config.PUBLIC_URL or origin, pid))
await hub.send(ws, screen_state(pid))
hub.ensure_ticker(pid)
hub.refresh(pid)
try:
await _hold(ws)
finally:
hub.screens.get(pid, {}).pop(ws, None)
hub.refresh(pid)
async def ws_admin(ws: WebSocket):
pid = ws.path_params["pid"]
p = db.poll(pid)
await ws.accept()
if not p or not await _auth_first_message(ws, lambda k: check_key(k, p["admin_hash"])):
await ws.close(code=4003)
return
hub.admins.setdefault(pid, set()).add(ws)
await hub.send(ws, admin_state(pid))
try:
await _hold(ws)
finally:
hub.admins.get(pid, set()).discard(ws)
async def ws_voter(ws: WebSocket):
pid = ws.path_params["pid"]
# cookie-authenticated socket: refuse cross-site handshakes
if not db.poll(pid) or not same_origin(ws):
await ws.close(code=4003)
return
v = current_voter(ws, pid)
await ws.accept()
if not v:
await hub.send(ws, {"type": "not_enrolled"})
await ws.close(code=4004)
return
hub.voters.setdefault(pid, {}).setdefault(v["id"], set()).add(ws)
await hub.send(ws, voter_state(pid, v))
try:
await _hold(ws)
finally:
conns = hub.voters.get(pid, {}).get(v["id"])
if conns is not None:
conns.discard(ws)
if not conns:
hub.voters[pid].pop(v["id"], None)
CSP = ("default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self'; "
"img-src 'self' data: blob:; media-src 'self' blob: mediastream:; connect-src 'self' ws: wss:; "
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'")
class SecurityHeaders:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
path = scope["path"]
async def wrapped(msg):
if msg["type"] == "http.response.start":
h = msg.setdefault("headers", [])
h += [
(b"content-security-policy", CSP.encode()),
(b"referrer-policy", b"no-referrer"),
(b"x-content-type-options", b"nosniff"),
(b"x-frame-options", b"DENY"),
(b"permissions-policy", b"camera=(self), microphone=(), geolocation=()"),
]
if not path.startswith("/static/vendor/"):
h.append((b"cache-control", b"no-store"))
if config.SECURE_COOKIES:
h.append((b"strict-transport-security", b"max-age=31536000"))
await send(msg)
await self.app(scope, receive, wrapped)
async def on_http_error(request: Request, exc: HTTPException):
if request.url.path.startswith("/api/"):
return JSONResponse({"error": exc.detail}, status_code=exc.status_code)
return Response(f"{exc.status_code} {exc.detail}", status_code=exc.status_code, media_type="text/plain")
_create_hash = ""
@contextlib.asynccontextmanager
async def lifespan(app):
global db, _create_hash
db = open_db()
if config.CREATE_PASSWORD:
_create_hash = sha(config.CREATE_PASSWORD)
beat = asyncio.get_running_loop().create_task(heartbeat())
yield
beat.cancel()
routes = [
Route("/", page("index.html")),
Route("/admin/{pid}", page("admin.html")),
Route("/screen/{pid}", page("screen.html")),
Route("/essai", page("essai.html")),
Route("/v/{pid}", page("vote.html")),
Route("/V/{pid}", lambda r: RedirectResponse(f"/v/{r.path_params['pid'].lower()}", status_code=301)),
Route("/api/config", public_config, methods=["GET"]),
Route("/api/polls", create_poll, methods=["POST"]),
Route("/api/trial", create_trial, methods=["POST"]),
Route("/api/polls/{pid}", admin_get, methods=["GET"]),
Route("/api/polls/{pid}", admin_patch, methods=["PATCH"]),
Route("/api/polls/{pid}/screen-key", admin_rotate_screen_key, methods=["POST"]),
Route("/api/polls/{pid}/questions", admin_add_question, methods=["POST"]),
Route("/api/polls/{pid}/questions/{qid:int}/{action}", admin_question_action, methods=["POST"]),
Route("/api/polls/{pid}/codes", admin_codes, methods=["GET", "POST"]),
Route("/api/polls/{pid}/export", admin_export, methods=["GET"]),
Route("/api/v/{pid}/me", voter_me, methods=["GET"]),
Route("/api/v/{pid}/scan", voter_scan, methods=["POST"]),
Route("/api/v/{pid}/code", voter_code, methods=["POST"]),
Route("/api/v/{pid}/vote", voter_vote, methods=["POST"]),
Route("/api/v/{pid}/rescue", voter_rescue, methods=["POST"]),
WebSocketRoute("/ws/{pid}/screen", ws_screen),
WebSocketRoute("/ws/{pid}/admin", ws_admin),
WebSocketRoute("/ws/{pid}/voter", ws_voter),
Mount("/static", StaticFiles(directory=STATIC), name="static"),
]
app = Starlette(
routes=routes,
middleware=[Middleware(SecurityHeaders)],
exception_handlers={HTTPException: on_http_error},
lifespan=lifespan,
)