RotatyVote: in-person anonymous voting with rotating QR enrollment
Starlette backend with sqlite, rotating HMAC QR tokens pushed to a key-protected projector page, multi-scan enrollment, optional one-time paper codes, anonymous ballots split from participation, live question push over websockets, e2e tests over HTTP and TLS.
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import socket
|
||||
|
||||
import uvicorn
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
def lan_ip():
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.connect(("10.255.255.255", 1))
|
||||
return s.getsockname()[0]
|
||||
except OSError:
|
||||
return "127.0.0.1"
|
||||
|
||||
|
||||
def main():
|
||||
scheme = "https" if config.TLS_CERT else "http"
|
||||
print(f"RotatyVote -> {scheme}://localhost:{config.PORT} (LAN: {scheme}://{lan_ip()}:{config.PORT})")
|
||||
if config.PUBLIC_URL:
|
||||
print(f"QR codes encode {config.PUBLIC_URL}")
|
||||
elif scheme == "http":
|
||||
print("warning: phones need HTTPS for the camera. set TLS_CERT/TLS_KEY or put a TLS proxy in front")
|
||||
uvicorn.run(
|
||||
"rotatyvote.app:app",
|
||||
host=config.HOST,
|
||||
port=config.PORT,
|
||||
ssl_certfile=config.TLS_CERT or None,
|
||||
ssl_keyfile=config.TLS_KEY or None,
|
||||
proxy_headers=config.BEHIND_PROXY,
|
||||
forwarded_allow_ips="*" if config.BEHIND_PROXY else None,
|
||||
ws="websockets-sansio",
|
||||
# access log would leak attempt/vote timing per client ip
|
||||
access_log=False,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,762 @@
|
||||
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, Response
|
||||
from starlette.routing import Mount, Route, WebSocketRoute
|
||||
from starlette.staticfiles import StaticFiles
|
||||
from starlette.websockets import WebSocket, WebSocketDisconnect
|
||||
|
||||
from . import config
|
||||
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"],
|
||||
},
|
||||
"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)
|
||||
return {"total": len(rows), "used": sum(r["used"] for r in rows)}
|
||||
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
return {"type": "state", "title": p["title"], "enrolled": True, "questions": qs}
|
||||
|
||||
|
||||
def qr_modules(url: str):
|
||||
qr = segno.make(url, error="m", micro=False)
|
||||
return ["".join("1" if b else "0" for b in row) for row in qr.matrix]
|
||||
|
||||
|
||||
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):
|
||||
try:
|
||||
await ws.send_text(json.dumps(msg, ensure_ascii=False))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
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):
|
||||
st = admin_state(pid)
|
||||
for ws in list(self.admins[pid]):
|
||||
await self.send(ws, st)
|
||||
if self.screens.get(pid):
|
||||
st = screen_state(pid)
|
||||
for ws in list(self.screens[pid]):
|
||||
await self.send(ws, st)
|
||||
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
|
||||
st = voter_state(pid, v)
|
||||
for ws in list(conns):
|
||||
await self.send(ws, st)
|
||||
|
||||
def ensure_ticker(self, pid):
|
||||
t = self.tickers.get(pid)
|
||||
if t and not t.done():
|
||||
return
|
||||
p = db.poll(pid)
|
||||
if p and p["enrollment_open"] 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 p["enrollment_open"] or not screens:
|
||||
return
|
||||
iv = p["interval_ms"]
|
||||
slot = current_slot(iv)
|
||||
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, "modules": qr_modules(url), "slot": slot,
|
||||
"interval_ms": iv, "valid_until": (slot + 1) * iv}
|
||||
for ws in conns:
|
||||
await self.send(ws, 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 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")
|
||||
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)
|
||||
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 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 "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"))
|
||||
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"]),
|
||||
"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="/")
|
||||
hub.refresh(pid)
|
||||
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 = verify_token(p["secret"], pid, p["interval_ms"], 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_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")
|
||||
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, 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)
|
||||
yield
|
||||
|
||||
|
||||
routes = [
|
||||
Route("/", page("index.html")),
|
||||
Route("/admin/{pid}", page("admin.html")),
|
||||
Route("/screen/{pid}", page("screen.html")),
|
||||
Route("/v/{pid}", page("vote.html")),
|
||||
Route("/api/config", public_config, methods=["GET"]),
|
||||
Route("/api/polls", create_poll, 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"]),
|
||||
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,
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
|
||||
HOST = os.environ.get("HOST", "0.0.0.0")
|
||||
PORT = int(os.environ.get("PORT", "8000"))
|
||||
# url encoded in the QR codes, eg https://vote.example.org
|
||||
# when empty the projector's own origin is used
|
||||
PUBLIC_URL = os.environ.get("PUBLIC_URL", "").rstrip("/")
|
||||
TLS_CERT = os.environ.get("TLS_CERT", "")
|
||||
TLS_KEY = os.environ.get("TLS_KEY", "")
|
||||
DB_PATH = os.environ.get("DB_PATH", "rotatyvote.db")
|
||||
# if set, creating a poll requires this password
|
||||
CREATE_PASSWORD = os.environ.get("CREATE_PASSWORD", "")
|
||||
# set to 1 when a TLS-terminating reverse proxy sits in front
|
||||
BEHIND_PROXY = os.environ.get("BEHIND_PROXY", "") == "1"
|
||||
|
||||
SECURE_COOKIES = bool(TLS_CERT) or PUBLIC_URL.startswith("https://") or BEHIND_PROXY
|
||||
|
||||
# extra time a code stays valid after its slot ends (network + decode latency)
|
||||
TOKEN_GRACE_MS = int(os.environ.get("TOKEN_GRACE_MS", "2500"))
|
||||
# slack on top of scans*interval to collect all scans of one attempt
|
||||
ATTEMPT_SLACK_MS = int(os.environ.get("ATTEMPT_SLACK_MS", "8000"))
|
||||
# once presence is proven, how long the voter has to type an access code
|
||||
CODE_ENTRY_TTL_S = 180
|
||||
|
||||
MIN_INTERVAL_MS = 300
|
||||
MAX_INTERVAL_MS = 5000
|
||||
MIN_SCANS = 2
|
||||
MAX_SCANS = 20
|
||||
@@ -0,0 +1,250 @@
|
||||
import json
|
||||
import secrets
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
|
||||
from . import config
|
||||
from .tokens import new_id, new_key, now_ms, sha
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS polls(
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
admin_hash TEXT NOT NULL,
|
||||
screen_hash TEXT NOT NULL,
|
||||
secret BLOB NOT NULL,
|
||||
interval_ms INTEGER NOT NULL,
|
||||
scans_required INTEGER NOT NULL,
|
||||
enrollment_open INTEGER NOT NULL DEFAULT 0,
|
||||
max_voters INTEGER,
|
||||
expected INTEGER,
|
||||
require_code INTEGER NOT NULL DEFAULT 0,
|
||||
focus_qid INTEGER,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
-- random ids + WITHOUT ROWID so storage order says nothing about enrollment or vote order
|
||||
CREATE TABLE IF NOT EXISTS voters(
|
||||
id TEXT PRIMARY KEY,
|
||||
poll_id TEXT NOT NULL,
|
||||
cred_hash TEXT NOT NULL UNIQUE
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS voters_poll ON voters(poll_id);
|
||||
CREATE TABLE IF NOT EXISTS access_codes(
|
||||
poll_id TEXT NOT NULL,
|
||||
code TEXT NOT NULL,
|
||||
used INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY(poll_id, code)
|
||||
) WITHOUT ROWID;
|
||||
CREATE TABLE IF NOT EXISTS questions(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
poll_id TEXT NOT NULL,
|
||||
position INTEGER NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
options TEXT NOT NULL,
|
||||
max_choices INTEGER NOT NULL DEFAULT 1,
|
||||
allow_blank INTEGER NOT NULL DEFAULT 1,
|
||||
state TEXT NOT NULL DEFAULT 'draft',
|
||||
results_public INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS questions_poll ON questions(poll_id);
|
||||
-- who took part, never what they chose
|
||||
CREATE TABLE IF NOT EXISTS participation(
|
||||
question_id INTEGER NOT NULL,
|
||||
voter_id TEXT NOT NULL,
|
||||
PRIMARY KEY(question_id, voter_id)
|
||||
) WITHOUT ROWID;
|
||||
-- what was chosen, never by whom. no timestamp on purpose
|
||||
CREATE TABLE IF NOT EXISTS ballots(
|
||||
id TEXT PRIMARY KEY,
|
||||
question_id INTEGER NOT NULL,
|
||||
choices TEXT NOT NULL
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS ballots_q ON ballots(question_id);
|
||||
"""
|
||||
|
||||
|
||||
class DB:
|
||||
def __init__(self, path: str):
|
||||
# all access happens on the event loop thread, so one connection is enough
|
||||
self.c = sqlite3.connect(path, isolation_level=None, check_same_thread=False)
|
||||
self.c.row_factory = sqlite3.Row
|
||||
# rollback journal (not WAL) so no log of recent inserts stays on disk
|
||||
self.c.execute("PRAGMA journal_mode=DELETE")
|
||||
self.c.execute("PRAGMA secure_delete=ON")
|
||||
self.c.execute("PRAGMA foreign_keys=ON")
|
||||
self.c.executescript(SCHEMA)
|
||||
|
||||
@contextmanager
|
||||
def tx(self):
|
||||
self.c.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
yield self.c
|
||||
self.c.execute("COMMIT")
|
||||
except BaseException:
|
||||
self.c.execute("ROLLBACK")
|
||||
raise
|
||||
|
||||
def one(self, sql, *args):
|
||||
return self.c.execute(sql, args).fetchone()
|
||||
|
||||
def all(self, sql, *args):
|
||||
return self.c.execute(sql, args).fetchall()
|
||||
|
||||
|
||||
def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters):
|
||||
pid = new_id()
|
||||
while self.one("SELECT 1 FROM polls WHERE id=?", pid):
|
||||
pid = new_id()
|
||||
admin_key, screen_key = new_key(), new_key()
|
||||
self.c.execute(
|
||||
"INSERT INTO polls(id,title,admin_hash,screen_hash,secret,interval_ms,scans_required,"
|
||||
"require_code,expected,max_voters,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(pid, title, sha(admin_key), sha(screen_key), secrets.token_bytes(32), interval_ms,
|
||||
scans_required, int(require_code), expected, max_voters, now_ms()),
|
||||
)
|
||||
return pid, admin_key, screen_key
|
||||
|
||||
def poll(self, pid):
|
||||
return self.one("SELECT * FROM polls WHERE id=?", pid)
|
||||
|
||||
def update_poll(self, pid, **fields):
|
||||
allowed = {"title", "interval_ms", "scans_required", "enrollment_open", "max_voters",
|
||||
"expected", "require_code", "focus_qid"}
|
||||
fields = {k: v for k, v in fields.items() if k in allowed}
|
||||
if not fields:
|
||||
return
|
||||
sets = ",".join(f"{k}=?" for k in fields)
|
||||
self.c.execute(f"UPDATE polls SET {sets} WHERE id=?", (*fields.values(), pid))
|
||||
|
||||
def voter_count(self, pid):
|
||||
return self.one("SELECT COUNT(*) n FROM voters WHERE poll_id=?", pid)["n"]
|
||||
|
||||
|
||||
def voter_by_cred(self, pid, cred):
|
||||
if not cred:
|
||||
return None
|
||||
return self.one("SELECT * FROM voters WHERE poll_id=? AND cred_hash=?", pid, sha(cred))
|
||||
|
||||
def enroll(self, pid, code=None):
|
||||
"""creates a voter atomically. returns (cred, error)"""
|
||||
with self.tx() as c:
|
||||
p = c.execute("SELECT * FROM polls WHERE id=?", (pid,)).fetchone()
|
||||
if not p["enrollment_open"]:
|
||||
return None, "closed"
|
||||
if p["max_voters"] is not None:
|
||||
n = c.execute("SELECT COUNT(*) FROM voters WHERE poll_id=?", (pid,)).fetchone()[0]
|
||||
if n >= p["max_voters"]:
|
||||
return None, "full"
|
||||
if p["require_code"]:
|
||||
norm = normalize_code(code or "")
|
||||
cur = c.execute(
|
||||
"UPDATE access_codes SET used=1 WHERE poll_id=? AND code=? AND used=0", (pid, norm))
|
||||
if cur.rowcount != 1:
|
||||
return None, "bad_code"
|
||||
cred = secrets.token_urlsafe(32)
|
||||
c.execute("INSERT INTO voters(id,poll_id,cred_hash) VALUES(?,?,?)",
|
||||
(secrets.token_hex(16), pid, sha(cred)))
|
||||
return cred, None
|
||||
|
||||
|
||||
def add_codes(self, pid, count):
|
||||
codes = []
|
||||
with self.tx() as c:
|
||||
while len(codes) < count:
|
||||
code = gen_code()
|
||||
try:
|
||||
c.execute("INSERT INTO access_codes(poll_id,code) VALUES(?,?)", (pid, code))
|
||||
codes.append(code)
|
||||
except sqlite3.IntegrityError:
|
||||
pass
|
||||
return codes
|
||||
|
||||
def codes(self, pid):
|
||||
return [dict(r) for r in self.all(
|
||||
"SELECT code, used FROM access_codes WHERE poll_id=? ORDER BY code", pid)]
|
||||
|
||||
|
||||
def add_question(self, pid, text, kind, options, max_choices, allow_blank):
|
||||
pos = self.one("SELECT COALESCE(MAX(position),0)+1 p FROM questions WHERE poll_id=?", pid)["p"]
|
||||
cur = self.c.execute(
|
||||
"INSERT INTO questions(poll_id,position,text,kind,options,max_choices,allow_blank) "
|
||||
"VALUES(?,?,?,?,?,?,?)",
|
||||
(pid, pos, text, kind, json.dumps(options, ensure_ascii=False), max_choices, int(allow_blank)),
|
||||
)
|
||||
return cur.lastrowid
|
||||
|
||||
def question(self, pid, qid):
|
||||
return self.one("SELECT * FROM questions WHERE poll_id=? AND id=?", pid, qid)
|
||||
|
||||
def questions(self, pid):
|
||||
return self.all("SELECT * FROM questions WHERE poll_id=? ORDER BY position", pid)
|
||||
|
||||
def set_question(self, qid, **fields):
|
||||
allowed = {"state", "results_public"}
|
||||
fields = {k: v for k, v in fields.items() if k in allowed}
|
||||
sets = ",".join(f"{k}=?" for k in fields)
|
||||
self.c.execute(f"UPDATE questions SET {sets} WHERE id=?", (*fields.values(), qid))
|
||||
|
||||
def delete_question(self, qid):
|
||||
self.c.execute("DELETE FROM questions WHERE id=? AND state='draft'", (qid,))
|
||||
|
||||
def participants(self, qid):
|
||||
return self.one("SELECT COUNT(*) n FROM participation WHERE question_id=?", qid)["n"]
|
||||
|
||||
def voted_qids(self, voter_id, pid):
|
||||
rows = self.all(
|
||||
"SELECT p.question_id FROM participation p JOIN questions q ON q.id=p.question_id "
|
||||
"WHERE p.voter_id=? AND q.poll_id=?", voter_id, pid)
|
||||
return {r[0] for r in rows}
|
||||
|
||||
def cast(self, pid, qid, voter_id, choices):
|
||||
"""participation + ballot in one tx. returns error string or None"""
|
||||
with self.tx() as c:
|
||||
q = c.execute("SELECT state FROM questions WHERE id=? AND poll_id=?", (qid, pid)).fetchone()
|
||||
if not q or q["state"] != "open":
|
||||
return "not_open"
|
||||
try:
|
||||
c.execute("INSERT INTO participation(question_id,voter_id) VALUES(?,?)", (qid, voter_id))
|
||||
except sqlite3.IntegrityError:
|
||||
return "already_voted"
|
||||
c.execute("INSERT INTO ballots(id,question_id,choices) VALUES(?,?,?)",
|
||||
(secrets.token_hex(16), qid, json.dumps(sorted(choices))))
|
||||
return None
|
||||
|
||||
def results(self, q):
|
||||
opts = json.loads(q["options"])
|
||||
counts = [0] * len(opts)
|
||||
blank = 0
|
||||
total = 0
|
||||
for r in self.all("SELECT choices FROM ballots WHERE question_id=?", q["id"]):
|
||||
total += 1
|
||||
ch = json.loads(r["choices"])
|
||||
if not ch:
|
||||
blank += 1
|
||||
for i in ch:
|
||||
if 0 <= i < len(counts):
|
||||
counts[i] += 1
|
||||
return {"counts": counts, "blank": blank, "ballots": total}
|
||||
|
||||
def ballots(self, qid):
|
||||
# pk is random so this order is meaningless, which is the point
|
||||
return [json.loads(r["choices"]) for r in self.all(
|
||||
"SELECT choices FROM ballots WHERE question_id=? ORDER BY id", qid)]
|
||||
|
||||
|
||||
CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
|
||||
|
||||
def gen_code():
|
||||
raw = "".join(secrets.choice(CODE_ALPHABET) for _ in range(8))
|
||||
return f"{raw[:4]}-{raw[4:]}"
|
||||
|
||||
|
||||
def normalize_code(s: str) -> str:
|
||||
s = "".join(ch for ch in s.upper() if ch.isalnum())
|
||||
return f"{s[:4]}-{s[4:8]}" if len(s) == 8 else s
|
||||
|
||||
|
||||
def open_db():
|
||||
return DB(config.DB_PATH)
|
||||
@@ -0,0 +1,58 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import time
|
||||
|
||||
ID_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789"
|
||||
|
||||
|
||||
def now_ms() -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
||||
|
||||
def new_id(n: int = 8) -> str:
|
||||
return "".join(secrets.choice(ID_ALPHABET) for _ in range(n))
|
||||
|
||||
|
||||
def new_key() -> str:
|
||||
return secrets.token_urlsafe(24)
|
||||
|
||||
|
||||
def sha(s: str) -> str:
|
||||
return hashlib.sha256(s.encode()).hexdigest()
|
||||
|
||||
|
||||
def check_key(given: str | None, stored_hash: str) -> bool:
|
||||
if not given:
|
||||
return False
|
||||
return hmac.compare_digest(sha(given), stored_hash)
|
||||
|
||||
|
||||
def _mac(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
|
||||
msg = f"{poll_id}:{interval_ms}:{slot}".encode()
|
||||
# 72 bits is plenty for a code that lives ~3s, keeps the QR small
|
||||
return base64.urlsafe_b64encode(hmac.new(secret, msg, hashlib.sha256).digest()[:9]).decode()
|
||||
|
||||
|
||||
def current_slot(interval_ms: int, at_ms: int | None = None) -> int:
|
||||
return (at_ms if at_ms is not None else now_ms()) // interval_ms
|
||||
|
||||
|
||||
def make_token(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
|
||||
return f"{slot}.{_mac(secret, poll_id, interval_ms, slot)}"
|
||||
|
||||
|
||||
def verify_token(secret: bytes, poll_id: str, interval_ms: int, token: str, grace_ms: int) -> int | None:
|
||||
"""returns the slot if the token is authentic and fresh, else None"""
|
||||
try:
|
||||
slot_s, mac = token.split(".", 1)
|
||||
slot = int(slot_s)
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
if not hmac.compare_digest(mac, _mac(secret, poll_id, interval_ms, slot)):
|
||||
return None
|
||||
age = now_ms() - slot * interval_ms
|
||||
if age < 0 or age > interval_ms + grace_ms:
|
||||
return None
|
||||
return slot
|
||||
Reference in New Issue
Block a user