Vote-time presence scan, rescue codes, websocket heartbeat
Each vote can require N fresh codes read off the projector (default 3, off for rooms without a projector); voters enrolled with a paper or rescue code are exempt. Rescue codes enroll a phone without camera. Projector keeps the QR up while such a vote is open. Server pings every socket every 25s so proxies keep them open. Composer no longer closes on enter. Schema migrates existing databases.
This commit is contained in:
+72
-6
@@ -71,6 +71,7 @@ def admin_state(pid):
|
||||
"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"],
|
||||
},
|
||||
"voters": db.voter_count(pid),
|
||||
"codes": codes_summary(pid),
|
||||
@@ -82,7 +83,24 @@ def admin_state(pid):
|
||||
|
||||
def codes_summary(pid):
|
||||
rows = db.codes(pid)
|
||||
return {"total": len(rows), "used": sum(r["used"] for r in rows)}
|
||||
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"""
|
||||
return p["vote_scans"] > 0 and has_open_question(p["id"])
|
||||
|
||||
|
||||
def needs_qr(p):
|
||||
return bool(p["enrollment_open"]) or presence_check(p)
|
||||
|
||||
|
||||
def screen_state(pid):
|
||||
@@ -96,6 +114,7 @@ def screen_state(pid):
|
||||
"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"],
|
||||
}
|
||||
|
||||
|
||||
@@ -108,7 +127,8 @@ def voter_state(pid, voter):
|
||||
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}
|
||||
scans = 0 if voter["via_code"] else p["vote_scans"]
|
||||
return {"type": "state", "title": p["title"], "enrolled": True, "questions": qs, "vote_scans": scans}
|
||||
|
||||
|
||||
def qr_modules(url: str):
|
||||
@@ -172,7 +192,7 @@ class Hub:
|
||||
if t and not t.done():
|
||||
return
|
||||
p = db.poll(pid)
|
||||
if p and p["enrollment_open"] and self.screens.get(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):
|
||||
@@ -180,7 +200,7 @@ class Hub:
|
||||
while True:
|
||||
p = db.poll(pid)
|
||||
screens = self.screens.get(pid)
|
||||
if not p or not p["enrollment_open"] or not screens:
|
||||
if not p or not needs_qr(p) or not screens:
|
||||
return
|
||||
iv = p["interval_ms"]
|
||||
slot = current_slot(iv)
|
||||
@@ -204,6 +224,17 @@ class Hub:
|
||||
hub = Hub()
|
||||
|
||||
|
||||
async def heartbeat():
|
||||
# proxies (cloudflare ~100s) drop idle websockets, keep every socket chatty
|
||||
while True:
|
||||
await asyncio.sleep(25)
|
||||
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]
|
||||
for ws in conns:
|
||||
await hub.send(ws, {"type": "ping"})
|
||||
|
||||
|
||||
async def body(request: Request) -> dict:
|
||||
raw = await request.body()
|
||||
if len(raw) > MAX_BODY:
|
||||
@@ -332,9 +363,10 @@ async def create_poll(request: Request):
|
||||
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")
|
||||
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)
|
||||
expected, max_voters, vote_scans)
|
||||
for q in questions:
|
||||
db.add_question(pid, *q)
|
||||
codes = int(d.get("codes") or 0)
|
||||
@@ -371,6 +403,8 @@ async def admin_patch(request: Request):
|
||||
upd["expected"] = opt_int(d["expected"], 1, 100000, "expected")
|
||||
if "require_code" in d:
|
||||
upd["require_code"] = int(bool(d["require_code"]))
|
||||
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):
|
||||
@@ -449,7 +483,7 @@ async def admin_codes(request: Request):
|
||||
require_admin(request, pid)
|
||||
if request.method == "POST":
|
||||
d = await body(request)
|
||||
db.add_codes(pid, clamp_int(d.get("count"), 1, 5000, "count"))
|
||||
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)})
|
||||
|
||||
@@ -549,6 +583,22 @@ async def voter_scan(request: Request):
|
||||
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)
|
||||
@@ -593,6 +643,19 @@ async def voter_vote(request: Request):
|
||||
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 = {verify_token(p["secret"], pid, p["interval_ms"], 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)
|
||||
@@ -727,7 +790,9 @@ async def lifespan(app):
|
||||
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 = [
|
||||
@@ -748,6 +813,7 @@ routes = [
|
||||
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),
|
||||
|
||||
@@ -23,6 +23,10 @@ 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
|
||||
|
||||
# codes needed to confirm each vote, 0 turns the check off
|
||||
DEFAULT_VOTE_SCANS = 3
|
||||
MAX_VOTE_SCANS = 5
|
||||
|
||||
MIN_INTERVAL_MS = 300
|
||||
MAX_INTERVAL_MS = 5000
|
||||
MIN_SCANS = 2
|
||||
|
||||
+38
-16
@@ -19,6 +19,7 @@ CREATE TABLE IF NOT EXISTS polls(
|
||||
max_voters INTEGER,
|
||||
expected INTEGER,
|
||||
require_code INTEGER NOT NULL DEFAULT 0,
|
||||
vote_scans INTEGER NOT NULL DEFAULT 0,
|
||||
focus_qid INTEGER,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
@@ -26,13 +27,15 @@ CREATE TABLE IF NOT EXISTS polls(
|
||||
CREATE TABLE IF NOT EXISTS voters(
|
||||
id TEXT PRIMARY KEY,
|
||||
poll_id TEXT NOT NULL,
|
||||
cred_hash TEXT NOT NULL UNIQUE
|
||||
cred_hash TEXT NOT NULL UNIQUE,
|
||||
via_code INTEGER NOT NULL DEFAULT 0
|
||||
) 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,
|
||||
rescue INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY(poll_id, code)
|
||||
) WITHOUT ROWID;
|
||||
CREATE TABLE IF NOT EXISTS questions(
|
||||
@@ -74,6 +77,18 @@ class DB:
|
||||
self.c.execute("PRAGMA secure_delete=ON")
|
||||
self.c.execute("PRAGMA foreign_keys=ON")
|
||||
self.c.executescript(SCHEMA)
|
||||
self._migrate()
|
||||
|
||||
def _migrate(self):
|
||||
# columns added after the first release, old databases get them here
|
||||
for table, col, ddl in (
|
||||
("polls", "vote_scans", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("voters", "via_code", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("access_codes", "rescue", "INTEGER NOT NULL DEFAULT 0"),
|
||||
):
|
||||
cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")}
|
||||
if col not in cols:
|
||||
self.c.execute(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}")
|
||||
|
||||
@contextmanager
|
||||
def tx(self):
|
||||
@@ -92,16 +107,16 @@ class DB:
|
||||
return self.c.execute(sql, args).fetchall()
|
||||
|
||||
|
||||
def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters):
|
||||
def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters, vote_scans=0):
|
||||
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(?,?,?,?,?,?,?,?,?,?,?)",
|
||||
"require_code,expected,max_voters,vote_scans,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()),
|
||||
scans_required, int(require_code), expected, max_voters, vote_scans, now_ms()),
|
||||
)
|
||||
return pid, admin_key, screen_key
|
||||
|
||||
@@ -110,7 +125,7 @@ class DB:
|
||||
|
||||
def update_poll(self, pid, **fields):
|
||||
allowed = {"title", "interval_ms", "scans_required", "enrollment_open", "max_voters",
|
||||
"expected", "require_code", "focus_qid"}
|
||||
"expected", "require_code", "focus_qid", "vote_scans"}
|
||||
fields = {k: v for k, v in fields.items() if k in allowed}
|
||||
if not fields:
|
||||
return
|
||||
@@ -126,8 +141,9 @@ class DB:
|
||||
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)"""
|
||||
def enroll(self, pid, code=None, rescue_code=None):
|
||||
"""creates a voter atomically. returns (cred, error)
|
||||
rescue_code: a one-time code that replaces the scan (broken camera)"""
|
||||
with self.tx() as c:
|
||||
p = c.execute("SELECT * FROM polls WHERE id=?", (pid,)).fetchone()
|
||||
if not p["enrollment_open"]:
|
||||
@@ -136,25 +152,31 @@ class DB:
|
||||
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 rescue_code is not None:
|
||||
cur = c.execute("UPDATE access_codes SET used=1 WHERE poll_id=? AND code=? AND used=0 AND rescue=1",
|
||||
(pid, normalize_code(rescue_code)))
|
||||
if cur.rowcount != 1:
|
||||
return None, "bad_code"
|
||||
elif p["require_code"]:
|
||||
cur = c.execute("UPDATE access_codes SET used=1 WHERE poll_id=? AND code=? AND used=0 AND rescue=0",
|
||||
(pid, normalize_code(code or "")))
|
||||
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)))
|
||||
# people who came in with a paper code skip the per-vote scan
|
||||
via_code = rescue_code is not None or bool(p["require_code"])
|
||||
c.execute("INSERT INTO voters(id,poll_id,cred_hash,via_code) VALUES(?,?,?,?)",
|
||||
(secrets.token_hex(16), pid, sha(cred), int(via_code)))
|
||||
return cred, None
|
||||
|
||||
|
||||
def add_codes(self, pid, count):
|
||||
def add_codes(self, pid, count, rescue=False):
|
||||
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))
|
||||
c.execute("INSERT INTO access_codes(poll_id,code,rescue) VALUES(?,?,?)", (pid, code, int(rescue)))
|
||||
codes.append(code)
|
||||
except sqlite3.IntegrityError:
|
||||
pass
|
||||
@@ -162,7 +184,7 @@ class DB:
|
||||
|
||||
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)]
|
||||
"SELECT code, used, rescue FROM access_codes WHERE poll_id=? ORDER BY code", pid)]
|
||||
|
||||
|
||||
def add_question(self, pid, text, kind, options, max_choices, allow_blank):
|
||||
|
||||
Reference in New Issue
Block a user